[ 
https://issues.apache.org/jira/browse/TINKERPOP-2774?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18146527#comment-18146527
 ] 

ASF GitHub Bot commented on TINKERPOP-2774:
-------------------------------------------

kenhuuu commented on code in PR #3527:
URL: https://github.com/apache/tinkerpop/pull/3527#discussion_r4608850536


##########
gremlin-python/src/main/python/gremlin_python/driver/async_protocol.py:
##########
@@ -0,0 +1,142 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+Asynchronous Gremlin Server WebSocket subprotocol implementation.
+"""
+import asyncio
+import base64
+import logging
+
+from gremlin_python.driver import request
+from gremlin_python.driver.protocol import (
+    ConfigurationError,
+    GremlinServerError,
+    GremlinServerWSProtocol,
+)
+
+log = logging.getLogger("gremlinpython")
+
+class AsyncGremlinServerWSProtocol(GremlinServerWSProtocol):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async version of GremlinServerWSProtocol.
+
+    Both write() and data_received() are coroutines that must be awaited.
+    The transport assigned via connection_made() must be an
+    AsyncAiohttpWSTransport (i.e. its write and read methods must be
+    coroutines).
+    """
+
+    async def write(self, request_id, request_message):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Serialize *request_message* and send it over the WebSocket.
+        """
+        message = self._message_serializer.serialize_message(
+            request_id, request_message
+        )
+        await self._transport.write(message)
+
+    async def data_received(self, message, results_dict):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Deserialize a raw WebSocket frame and dispatch results.
+
+        Deserialization is offloaded to the default executor so that the event
+        loop is not blocked by CPU-bound work.
+
+        Returns the Gremlin Server response status code (200, 204, or 206).
+        Raises GremlinServerError for error status codes.
+        """
+        if message is None:
+            log.error("Received empty message from server.")
+            raise GremlinServerError(
+                {
+                    "code": 500,
+                    "message": "Server disconnected - please try to reconnect",
+                    "attributes": {},
+                }
+            )
+
+        loop = asyncio.get_running_loop()
+        message = await loop.run_in_executor(
+            None, self._message_serializer.deserialize_message, message
+        )
+
+        request_id = message["requestId"]
+        result_set = results_dict.get(request_id)

Review Comment:
   Please fail when a response’s requestId has no matching entry in 
`results_dict`. The sync protocol raises in this situation, but the async 
implementation’s `result_set is not None` guards discard the response and 
return its success status. `_receive()` can then complete the pending request 
with an empty result and leave stale state in `_results`. Please raise a 
protocol/connection error, invalidate the connection, and add coverage for 
mismatched IDs with 200, 204, and 206 responses.



##########
gremlin-python/src/main/python/gremlin_python/driver/async_protocol.py:
##########
@@ -0,0 +1,142 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+Asynchronous Gremlin Server WebSocket subprotocol implementation.
+"""
+import asyncio
+import base64
+import logging
+
+from gremlin_python.driver import request
+from gremlin_python.driver.protocol import (
+    ConfigurationError,
+    GremlinServerError,
+    GremlinServerWSProtocol,
+)
+
+log = logging.getLogger("gremlinpython")
+
+class AsyncGremlinServerWSProtocol(GremlinServerWSProtocol):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async version of GremlinServerWSProtocol.
+
+    Both write() and data_received() are coroutines that must be awaited.
+    The transport assigned via connection_made() must be an
+    AsyncAiohttpWSTransport (i.e. its write and read methods must be
+    coroutines).
+    """
+
+    async def write(self, request_id, request_message):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Serialize *request_message* and send it over the WebSocket.
+        """
+        message = self._message_serializer.serialize_message(
+            request_id, request_message
+        )
+        await self._transport.write(message)
+
+    async def data_received(self, message, results_dict):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Deserialize a raw WebSocket frame and dispatch results.
+
+        Deserialization is offloaded to the default executor so that the event
+        loop is not blocked by CPU-bound work.
+
+        Returns the Gremlin Server response status code (200, 204, or 206).
+        Raises GremlinServerError for error status codes.
+        """
+        if message is None:
+            log.error("Received empty message from server.")
+            raise GremlinServerError(
+                {
+                    "code": 500,
+                    "message": "Server disconnected - please try to reconnect",
+                    "attributes": {},
+                }
+            )
+
+        loop = asyncio.get_running_loop()
+        message = await loop.run_in_executor(
+            None, self._message_serializer.deserialize_message, message
+        )
+
+        request_id = message["requestId"]
+        result_set = results_dict.get(request_id)
+        status_code = message["status"]["code"]
+        aggregate_to = message["result"]["meta"].get("aggregateTo", "list")
+        data = message["result"]["data"]
+
+        if result_set is not None:
+            result_set.aggregate_to = aggregate_to
+
+        if status_code == 407:

Review Comment:
   Please add async authentication coverage equivalent to the existing sync 
driver tests. At minimum, exercise Basic and Kerberos authentication through 
both AsyncClient and AsyncDriverRemoteConnection, including awaited cleanup, so 
this async-specific 407 handshake is validated end to end.



##########
gremlin-python/src/main/python/gremlin_python/driver/async_driver_remote_connection.py:
##########
@@ -0,0 +1,369 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+Asynchronous remote connection backed by AsyncClient.
+"""
+import asyncio
+import logging
+import uuid
+
+from gremlin_python.driver import serializer
+from gremlin_python.driver.async_client import AsyncClient
+from gremlin_python.process.strategies import OptionsStrategy
+from gremlin_python.process.traversal import Bytecode
+
+log = logging.getLogger("gremlinpython")
+
+
+class AsyncDriverRemoteConnection:
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async remote connection backed by AsyncClient.
+
+    Primary entry point for the async Gremlin driver.  Works with
+    async_traversal() to provide an async traversal DSL::
+
+        async with AsyncDriverRemoteConnection("ws://localhost:8182/gremlin", 
"g") as rc:
+            g = async_traversal().with_remote(rc)
+            names = await g.V().has_label("person").values("name").to_list()
+
+    Features:
+
+    * Per-connection WebSocket keepalive pings (see *ping_interval*).
+    * *query_timeout* sets a default evaluationTimeout on every request.
+
+    Parameters
+    ----------
+    url:
+        WebSocket endpoint, e.g. ws://localhost:8182/gremlin.
+    traversal_source:
+        Gremlin traversal source name (default "g").
+    protocol_factory:
+        Forwarded to AsyncClient.
+    transport_factory:
+        Forwarded to AsyncClient.
+    pool_size:
+        Number of concurrent WebSocket connections (default 8).
+    message_serializer:
+        Serializer instance (default GraphBinarySerializersV1).
+    username, password:
+        Credentials for SASL/basic authentication.
+    kerberized_service:
+        Kerberos service principal.
+    headers:
+        Extra HTTP headers for every WebSocket handshake.
+    session:
+        Session UUID string to enable server-side sessions.
+    enable_user_agent_on_connect:
+        Send the driver user-agent header (default True).
+    enable_compression:
+        Enable WebSocket per-message deflate compression (default False).
+    graphson_reader, graphson_writer:
+        Optional custom GraphSON reader and writer used when
+        *message_serializer* is not explicitly provided.
+    ping_interval:
+        Seconds between keepalive pings (default 60, 0 to disable).
+    query_timeout:
+        Default query timeout in seconds applied to every request as
+        evaluationTimeout.  Per-request options override this.
+    **transport_kwargs:
+        Extra keyword arguments forwarded to the default transport.
+    """
+
+    def __init__(
+        self,
+        url,
+        traversal_source="g",
+        protocol_factory=None,
+        transport_factory=None,
+        pool_size=None,
+        message_serializer=None,
+        username="",
+        password="",
+        kerberized_service="",
+        headers=None,
+        session=None,
+        enable_user_agent_on_connect=True,
+        enable_compression=False,
+        graphson_reader=None,
+        graphson_writer=None,
+        ping_interval=60,
+        query_timeout=None,

Review Comment:
   TinkerPop doesn't really have a query timeout concept right now but this 
seems to be hooked into evaluationTimeout so that's probably OK since this is 
experimental. However, the unit mismatches as this seems to be seconds while 
evaluationTimeout is milliseconds. Can you change `query_timeout` to also be 
milliseconds to match?



##########
gremlin-python/src/main/python/gremlin_python/driver/async_connection.py:
##########
@@ -0,0 +1,220 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+Native-async WebSocket connection managed by AsyncClient.
+"""
+import asyncio
+import logging
+import uuid
+
+from gremlin_python.driver import useragent
+from gremlin_python.driver.async_resultset import AsyncResultSet
+
+log = logging.getLogger("gremlinpython")
+
+
+class AsyncConnection:
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Native-async WebSocket connection with keepalive.
+
+    Features:
+
+    * Ping keepalive: a background asyncio.Task sends a WebSocket
+      ping every *ping_interval* seconds to prevent the server or intermediate
+      proxies from closing idle connections.
+
+    Parameters
+    ----------
+    url:
+        WebSocket endpoint.
+    traversal_source:
+        Gremlin traversal source name (e.g. "g").
+    protocol:
+        An AsyncGremlinServerWSProtocol instance.
+    transport_factory:
+        Zero-argument callable returning an AsyncAiohttpWSTransport.
+    pool:
+        The asyncio.Queue that owns this connection.
+    headers:
+        Extra HTTP headers sent during the WebSocket handshake.
+    enable_user_agent_on_connect:
+        Whether to send the driver user-agent header.
+    ping_interval:
+        Seconds between WebSocket ping frames (default 60, 0 to disable).
+    """
+
+    def __init__(self, url, traversal_source, protocol, transport_factory,
+                 pool, headers=None, enable_user_agent_on_connect=True,
+                 ping_interval=60):
+        self._url = url
+        self._headers = headers
+        self._traversal_source = traversal_source
+        self._protocol = protocol
+        self._transport_factory = transport_factory
+        self._transport = None
+        self._pool = pool
+        self._results = {}
+        self._inited = False
+        if enable_user_agent_on_connect:
+            self._add_header(useragent.userAgentHeader, useragent.userAgent)
+        self._ping_interval = ping_interval
+        self._ping_task = None
+        self._receive_task = None
+
+    def _add_header(self, key, value):
+        if self._headers is None:
+            self._headers = dict()
+        if key.lower() not in [k.lower() for k in self._headers.keys()]:
+            self._headers[key] = value
+
+    # ------------------------------------------------------------------
+    # Lifecycle
+    # ------------------------------------------------------------------
+
+    async def connect(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Open (or re-open) the WebSocket connection.
+        """
+        if self._ping_task is not None:
+            self._ping_task.cancel()
+            self._ping_task = None
+        if self._transport is not None:
+            await self._transport.close()
+        self._transport = self._transport_factory()
+        await self._transport.connect(self._url, self._headers)
+        self._protocol.connection_made(self._transport)
+        self._inited = True
+        if self._ping_interval > 0:
+            self._ping_task = asyncio.create_task(self._ping_forever())
+
+    async def close(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Close the connection and stop its background tasks.
+        """
+        await asyncio.shield(self._close())
+
+    async def _close(self):
+        if self._ping_task is not None:
+            self._ping_task.cancel()
+            self._ping_task = None
+        if self._receive_task is not None:
+            self._receive_task.cancel()
+            await asyncio.gather(self._receive_task, return_exceptions=True)
+        try:
+            if self._transport is not None:
+                await self._transport.close()
+        finally:
+            self._inited = False
+            self._results.clear()
+
+    # ------------------------------------------------------------------
+    # Keepalive
+    # ------------------------------------------------------------------
+
+    async def _ping_forever(self):
+        """Send periodic WebSocket ping frames until cancelled or the 
transport dies."""
+        while True:
+            try:
+                await asyncio.sleep(self._ping_interval)
+                await self._transport.ping()

Review Comment:
   Could this use aiohttp’s existing `heartbeat` support instead of maintaining 
a separate ping loop? `ping()` is not part of AbstractBaseTransport, so a 
custom transport satisfying the documented transport contract will fail here 
after the default interval. Using `heartbeat` would also avoid duplicate 
keepalive mechanisms and custom task-lifecycle handling.



##########
gremlin-python/src/main/python/gremlin_python/driver/async_graph_traversal.py:
##########
@@ -0,0 +1,489 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+Async traversal layer for gremlin-python.
+
+Async counterpart for the standard traversal() factory::
+
+    async with AsyncDriverRemoteConnection("ws://localhost:8182/gremlin", "g") 
as rc:
+        g = async_traversal().with_remote(rc)
+
+        names  = await g.V().has_label("person").values("name").to_list()
+        count  = await g.V().count().next()
+        await  g.add_v("person").property("name", "saturn").iterate()
+
+        async with await g.tx() as gtx:
+            await gtx.add_v("person").property("name", "pluto").iterate()
+            # commits on clean exit, rolls back on exception
+"""
+import asyncio
+import copy
+import logging
+
+from gremlin_python.process.graph_traversal import GraphTraversal, 
GraphTraversalSource
+from gremlin_python.process.traversal import (
+    Bytecode, Traversal, TraversalStrategies, TraversalStrategy,
+)
+from gremlin_python.structure.graph import Graph
+
+log = logging.getLogger("gremlinpython")
+
+
+# ---------------------------------------------------------------------------
+# Public factory
+# ---------------------------------------------------------------------------
+
+def async_traversal():
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Return an _AsyncAnonymousTraversalSource.
+
+    Use in place of traversal() when working with AsyncDriverRemoteConnection.
+    """
+    return _AsyncAnonymousTraversalSource()
+
+
+class _AsyncAnonymousTraversalSource:
+    def with_remote(self, remote_connection):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Bind *remote_connection* and return an AsyncGraphTraversalSource.
+        """
+        return AsyncGraphTraversalSource(
+            Graph(),
+            AsyncTraversalStrategies(),
+            remote_connection=remote_connection,
+        )
+
+
+# ---------------------------------------------------------------------------
+# Strategy pipeline (async)
+# ---------------------------------------------------------------------------
+
+class AsyncTraversalStrategies(TraversalStrategies):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async-aware strategy pipeline.
+
+    Calls ``await strategy.apply(traversal)`` for coroutine strategies and
+    ``strategy.apply(traversal)`` for plain sync strategies so both can 
coexist.
+    """
+
+    async def apply_strategies(self, traversal):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release."""
+        for strategy in self.traversal_strategies:
+            if asyncio.iscoroutinefunction(strategy.apply):
+                await strategy.apply(traversal)
+            else:
+                strategy.apply(traversal)
+
+
+class AsyncRemoteStrategy(TraversalStrategy):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Client-side strategy that submits bytecode to the remote server 
asynchronously.
+
+    Registered with the ``py:AsyncRemoteStrategy`` fqcn so it is never sent
+    to the server as part of the serialized traversal.
+    """
+
+    def __init__(self, remote_connection):
+        super().__init__(fqcn="py:AsyncRemoteStrategy")
+        self.remote_connection = remote_connection
+
+    async def apply(self, traversal):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release."""
+        if traversal.traversers is None:
+            remote_traversal = await 
self.remote_connection.submit(traversal.bytecode)
+            traversal.remote_results = remote_traversal
+            traversal.traversers = remote_traversal.traversers
+
+
+# ---------------------------------------------------------------------------
+# Traversal base (async terminal steps)
+# ---------------------------------------------------------------------------
+
+class AsyncTraversal(Traversal):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Base traversal class that replaces blocking terminal steps with coroutines.
+
+    Concrete subclasses must be used with AsyncTraversalStrategies so that
+    apply_strategies() can be awaited inside __anext__().
+    """
+
+    # Prevent accidental sync iteration.
+    def __next__(self):
+        raise NotImplementedError(
+            "AsyncTraversal does not support synchronous iteration. "
+            "Use 'async for', 'await to_list()', or 'await next()'."
+        )
+
+    # ------------------------------------------------------------------
+    # Async iteration protocol
+    # ------------------------------------------------------------------
+
+    def __aiter__(self):
+        return self
+
+    async def __anext__(self):
+        try:
+            if self.traversers is None:
+                await self.traversal_strategies.apply_strategies(self)
+            if self.last_traverser is None:
+                # StopAsyncIteration propagates naturally when the result set 
is exhausted.
+                self.last_traverser = await self.traversers.__anext__()
+            obj = self.last_traverser.object
+            self.last_traverser.bulk -= 1
+            if self.last_traverser.bulk <= 0:
+                self.last_traverser = None
+            return obj
+        except StopAsyncIteration:
+            raise
+        except BaseException:
+            self.traversers = None
+            self.last_traverser = None
+            raise
+
+    # ------------------------------------------------------------------
+    # Async terminal steps
+    # ------------------------------------------------------------------
+
+    async def to_list(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Execute the traversal and return all results as a list.
+        """
+        results = []
+        async for item in self:
+            results.append(item)
+        return results
+
+    async def to_set(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Execute the traversal and return all results as a set.
+        """
+        return set(await self.to_list())
+
+    async def next(self, amount=None):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Execute and return the first result, or the first *amount* results.
+
+        Raises StopAsyncIteration when *amount* is None and the result set is
+        empty.
+        """
+        if amount is None:
+            return await self.__anext__()
+        results = []
+        for _ in range(amount):
+            try:
+                results.append(await self.__anext__())
+            except StopAsyncIteration:
+                break
+        return results
+
+    async def iterate(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Execute the traversal, discarding all results.
+
+        Use for write operations (add_v, add_e, property, ...) where no return
+        value is needed.
+        """
+        if (
+            not self.bytecode.step_instructions
+            or self.bytecode.step_instructions[-1][0] != "discard"
+        ):
+            self.bytecode.add_step("discard")
+        while True:
+            try:
+                await self.next_traverser()
+            except StopAsyncIteration:
+                return self
+
+    async def has_next(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Return True if the traversal produces at least one result.
+        """
+        try:
+            if self.traversers is None:
+                await self.traversal_strategies.apply_strategies(self)
+            if self.last_traverser is None:
+                try:
+                    self.last_traverser = await self.traversers.__anext__()
+                except StopAsyncIteration:
+                    return False
+            return self.last_traverser is not None and 
self.last_traverser.bulk > 0
+        except BaseException:
+            self.traversers = None
+            self.last_traverser = None
+            raise
+
+    async def next_traverser(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Return the next raw Traverser.
+        """
+        try:
+            if self.traversers is None:
+                await self.traversal_strategies.apply_strategies(self)
+            if self.last_traverser is None:
+                return await self.traversers.__anext__()
+            temp = self.last_traverser
+            self.last_traverser = None
+            return temp
+        except StopAsyncIteration:
+            raise
+        except BaseException:
+            self.traversers = None
+            self.last_traverser = None
+            raise
+
+
+# ---------------------------------------------------------------------------
+# Concrete traversal classes
+# ---------------------------------------------------------------------------
+
+class AsyncGraphTraversal(GraphTraversal, AsyncTraversal):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async graph traversal.
+
+    Inherits all Gremlin DSL steps from GraphTraversal and async terminal
+    steps from AsyncTraversal via Python's MRO.
+
+    MRO: AsyncGraphTraversal -> GraphTraversal -> AsyncTraversal -> Traversal 
-> object
+
+    Because GraphTraversal does not define terminal steps directly (it
+    inherits them from Traversal), Python finds AsyncTraversal's async
+    versions first in the MRO before reaching Traversal's sync versions.
+    """
+
+    def clone(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release."""
+        return AsyncGraphTraversal(self.graph, self.traversal_strategies, 
copy.deepcopy(self.bytecode))
+
+
+class AsyncRemoteTraversal(AsyncTraversal):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Holds the AsyncResultSet returned by AsyncDriverRemoteConnection.submit().
+
+    traversers is set directly to the result set; strategies are never
+    applied (there is nothing to apply on an already-executed traversal).
+    """
+
+    def __init__(self, traversers):
+        super().__init__(None, None, None)
+        self.traversers = traversers
+
+
+# ---------------------------------------------------------------------------
+# Traversal source
+# ---------------------------------------------------------------------------
+
+class AsyncGraphTraversalSource(GraphTraversalSource):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async traversal source.
+
+    All spawned traversals are AsyncGraphTraversal instances.
+    Configuration steps (with_bulk(), with_path(), ...) return a new
+    AsyncGraphTraversalSource.
+
+    Use async_traversal() to create one::
+
+        g = async_traversal().with_remote(rc)
+    """
+
+    def __init__(self, graph, traversal_strategies, bytecode=None, 
remote_connection=None):
+        # Call super WITHOUT remote_connection to avoid RemoteStrategy being 
added.
+        super().__init__(graph, traversal_strategies, bytecode)
+        self.graph_traversal = AsyncGraphTraversal
+        self.remote_connection = remote_connection
+        if remote_connection is not None:
+            
self.traversal_strategies.add_strategies([AsyncRemoteStrategy(remote_connection)])
+
+    def get_graph_traversal_source(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Return a copy of this source (used by configuration steps).
+        """
+        # Strategies are copied — do NOT pass remote_connection to avoid
+        # registering AsyncRemoteStrategy a second time.
+        return AsyncGraphTraversalSource(
+            self.graph,
+            AsyncTraversalStrategies(self.traversal_strategies),
+            Bytecode(self.bytecode),
+        )
+
+    def get_graph_traversal(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Return a fresh AsyncGraphTraversal for this source.
+        """
+        return AsyncGraphTraversal(
+            self.graph,
+            self.traversal_strategies,
+            Bytecode(self.bytecode),
+        )
+
+    async def tx(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Return an AsyncTransaction for this connection.
+
+        Raises if the connection is already session-bound.
+        """
+        strategy = next(
+            (s for s in self.traversal_strategies.traversal_strategies
+             if isinstance(s, AsyncRemoteStrategy)),
+            None,
+        )
+        if strategy is None:
+            raise Exception("No remote connection configured on this traversal 
source")
+        if strategy.remote_connection.is_session_bound():
+            raise Exception(
+                "Cannot open a transaction on an already session-bound 
connection"
+            )
+        return AsyncTransaction(self, strategy.remote_connection)
+
+
+# ---------------------------------------------------------------------------
+# Transaction
+# ---------------------------------------------------------------------------
+
+class AsyncTransaction:
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async transaction over a session-bound connection.
+
+    Supports the async context-manager protocol::
+
+        async with await g.tx() as gtx:
+            await gtx.add_v("person").property("name", "pluto").iterate()
+            # commits on clean exit; rolls back on exception
+
+    Or manage it explicitly::
+
+        tx = await g.tx()
+        gtx = await tx.begin()
+        try:
+            await gtx.add_v("person").property("name", "pluto").iterate()
+            await tx.commit()
+        except Exception:
+            await tx.rollback()
+    """
+
+    def __init__(self, g, remote_connection):
+        self._g = g
+        self._remote_connection = remote_connection
+        self._session_connection = None
+        self._gtx = None
+        self._is_open = False
+        self._mutex = asyncio.Lock()
+
+    @property
+    def is_open(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release."""
+        if (
+            self._session_connection is not None
+            and self._session_connection.is_closed()
+        ) or self._remote_connection.is_closed():
+            self._is_open = False
+        return self._is_open
+
+    @property
+    def gtx(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release."""
+        if self._gtx is None:
+            raise Exception("Transaction not started — call begin() first")
+        return self._gtx
+
+    async def begin(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Open a session and return a session-bound AsyncGraphTraversalSource.
+        """
+        async with self._mutex:
+            if self.is_open:
+                raise Exception("Transaction is already open")
+            self._session_connection = self._remote_connection.create_session()
+            strategies = AsyncTraversalStrategies()
+            
strategies.add_strategies([AsyncRemoteStrategy(self._session_connection)])
+            self._gtx = AsyncGraphTraversalSource(
+                self._g.graph,
+                strategies,
+                self._g.bytecode,
+            )
+            self._is_open = True
+            return self._gtx
+
+    async def commit(self):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Commit the transaction and close the session.
+        """
+        async with self._mutex:
+            if not self.is_open:
+                raise Exception("Transaction is not open")
+            await self._session_connection.commit()

Review Comment:
   Please ensure session cleanup runs in a cancellation-safe finally for both 
`commit()` and `rollback()`. If this `await` raises or is cancelled, 
`_close_session()` is skipped, leaving the transaction marked open and the 
child retained by the parent; its server session may remain until explicit 
shutdown or session timeout. Preserve the terminal-operation exception while 
still closing/untracking the child, and add error/cancellation coverage.



##########
gremlin-python/src/main/python/gremlin_python/driver/async_client.py:
##########
@@ -0,0 +1,326 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+Native-async Gremlin client using WebSocket transport.
+"""
+import asyncio
+import logging
+
+from gremlin_python.driver import request, serializer
+from gremlin_python.driver.async_connection import AsyncConnection
+from gremlin_python.driver.async_protocol import AsyncGremlinServerWSProtocol
+from gremlin_python.driver.aiohttp.async_transport import 
AsyncAiohttpWSTransport
+from gremlin_python.process import traversal
+
+log = logging.getLogger("gremlinpython")
+
+
+class AsyncClient:
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Native-async Gremlin client using WebSocket transport.
+
+    The connection pool is an asyncio.Queue and all submit/close methods are
+    coroutines that must be awaited.
+
+    Features:
+
+    * Each connection runs a background WebSocket ping to prevent idle
+      disconnects (configurable via ping_interval).
+    * default_request_options are merged into every request so options
+      like evaluationTimeout can be set once per client.
+
+    Usage::
+
+        async with AsyncClient("ws://localhost:8182/gremlin", "g") as client:
+            result_set = await client.submit("g.V().count()")
+            print(await result_set.all())
+
+    Parameters
+    ----------
+    url:
+        WebSocket endpoint, e.g. ws://localhost:8182/gremlin.
+    traversal_source:
+        Gremlin traversal source name (default "g").
+    protocol_factory:
+        Zero-argument callable returning an AsyncGremlinServerWSProtocol.
+    transport_factory:
+        Zero-argument callable returning an AsyncAiohttpWSTransport.
+    pool_size:
+        Number of concurrent WebSocket connections (default 8; forced to 1
+        in session mode).
+    message_serializer:
+        Serializer to use (default GraphBinarySerializersV1).
+    username, password:
+        Credentials for SASL/basic authentication.
+    kerberized_service:
+        Kerberos service principal for Kerberos authentication.
+    headers:

Review Comment:
   Could this document that headers must be a mutable mapping, such as 
`dict[str, str]`? Unlike the sync client, list-of-pair headers are not 
supported. Please make the same clarification on 
`AsyncDriverRemoteConnection.headers`



##########
gremlin-python/src/main/python/gremlin_python/driver/async_graph_traversal.py:
##########
@@ -0,0 +1,489 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+"""Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+Async traversal layer for gremlin-python.
+
+Async counterpart for the standard traversal() factory::
+
+    async with AsyncDriverRemoteConnection("ws://localhost:8182/gremlin", "g") 
as rc:
+        g = async_traversal().with_remote(rc)
+
+        names  = await g.V().has_label("person").values("name").to_list()
+        count  = await g.V().count().next()
+        await  g.add_v("person").property("name", "saturn").iterate()
+
+        async with await g.tx() as gtx:
+            await gtx.add_v("person").property("name", "pluto").iterate()
+            # commits on clean exit, rolls back on exception
+"""
+import asyncio
+import copy
+import logging
+
+from gremlin_python.process.graph_traversal import GraphTraversal, 
GraphTraversalSource
+from gremlin_python.process.traversal import (
+    Bytecode, Traversal, TraversalStrategies, TraversalStrategy,
+)
+from gremlin_python.structure.graph import Graph
+
+log = logging.getLogger("gremlinpython")
+
+
+# ---------------------------------------------------------------------------
+# Public factory
+# ---------------------------------------------------------------------------
+
+def async_traversal():
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Return an _AsyncAnonymousTraversalSource.
+
+    Use in place of traversal() when working with AsyncDriverRemoteConnection.
+    """
+    return _AsyncAnonymousTraversalSource()
+
+
+class _AsyncAnonymousTraversalSource:
+    def with_remote(self, remote_connection):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release.
+
+        Bind *remote_connection* and return an AsyncGraphTraversalSource.
+        """
+        return AsyncGraphTraversalSource(
+            Graph(),
+            AsyncTraversalStrategies(),
+            remote_connection=remote_connection,
+        )
+
+
+# ---------------------------------------------------------------------------
+# Strategy pipeline (async)
+# ---------------------------------------------------------------------------
+
+class AsyncTraversalStrategies(TraversalStrategies):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Async-aware strategy pipeline.
+
+    Calls ``await strategy.apply(traversal)`` for coroutine strategies and
+    ``strategy.apply(traversal)`` for plain sync strategies so both can 
coexist.
+    """
+
+    async def apply_strategies(self, traversal):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release."""
+        for strategy in self.traversal_strategies:
+            if asyncio.iscoroutinefunction(strategy.apply):
+                await strategy.apply(traversal)
+            else:
+                strategy.apply(traversal)
+
+
+class AsyncRemoteStrategy(TraversalStrategy):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Client-side strategy that submits bytecode to the remote server 
asynchronously.
+
+    Registered with the ``py:AsyncRemoteStrategy`` fqcn so it is never sent
+    to the server as part of the serialized traversal.
+    """
+
+    def __init__(self, remote_connection):
+        super().__init__(fqcn="py:AsyncRemoteStrategy")
+        self.remote_connection = remote_connection
+
+    async def apply(self, traversal):
+        """Experimental API. This API may have breaking changes or be removed 
in a subsequent minor release."""
+        if traversal.traversers is None:
+            remote_traversal = await 
self.remote_connection.submit(traversal.bytecode)
+            traversal.remote_results = remote_traversal
+            traversal.traversers = remote_traversal.traversers
+
+
+# ---------------------------------------------------------------------------
+# Traversal base (async terminal steps)
+# ---------------------------------------------------------------------------
+
+class AsyncTraversal(Traversal):
+    """Experimental API. This API may have breaking changes or be removed in a 
subsequent minor release.
+
+    Base traversal class that replaces blocking terminal steps with coroutines.
+
+    Concrete subclasses must be used with AsyncTraversalStrategies so that
+    apply_strategies() can be awaited inside __anext__().
+    """
+
+    # Prevent accidental sync iteration.
+    def __next__(self):
+        raise NotImplementedError(
+            "AsyncTraversal does not support synchronous iteration. "
+            "Use 'async for', 'await to_list()', or 'await next()'."
+        )
+
+    # ------------------------------------------------------------------
+    # Async iteration protocol
+    # ------------------------------------------------------------------
+
+    def __aiter__(self):
+        return self
+
+    async def __anext__(self):
+        try:
+            if self.traversers is None:
+                await self.traversal_strategies.apply_strategies(self)
+            if self.last_traverser is None:
+                # StopAsyncIteration propagates naturally when the result set 
is exhausted.
+                self.last_traverser = await self.traversers.__anext__()
+            obj = self.last_traverser.object
+            self.last_traverser.bulk -= 1
+            if self.last_traverser.bulk <= 0:
+                self.last_traverser = None
+            return obj
+        except StopAsyncIteration:
+            raise
+        except BaseException:
+            self.traversers = None

Review Comment:
   Resetting traversers to `None` makes the next terminal call submit the 
entire traversal again. Once execution has started, the outcome may be 
ambiguous and results may already have been consumed, so resubmission can 
replay results or duplicate mutations. Please retain a failed state that 
re-raises the original error and require a fresh traversal for explicit 
retries. The same concern applies to the resets in `has_next()` and 
`next_traverser()`.





> Full async/await support in gremlin-python
> ------------------------------------------
>
>                 Key: TINKERPOP-2774
>                 URL: https://issues.apache.org/jira/browse/TINKERPOP-2774
>             Project: TinkerPop
>          Issue Type: Improvement
>          Components: python
>    Affects Versions: 3.5.3
>            Reporter: Ken Hu
>            Priority: Minor
>
> Recently, there have been multiple instances of users asking about issues 
> with event loops and aiohttp. This discussion nearly always ends up with the 
> user requesting for async/await support in gremlin-python. This means full 
> compatibility with asyncio and not needing to use threads.
> Async/await support is also a feature that those using newer, asynchronous 
> web frameworks are asking for as gremlin-python can be a performance 
> bottleneck due to its lack of support for async/await.
> My intention is that we can use this issue as a means of gauging the interest 
> from the community for this feature. If you are interested in having 
> gremlin-python support async/await then please leave a comment below.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to