diff --git a/src_cpp/include/py_handle_state.h b/src_cpp/include/py_handle_state.h index 9a60b25..7ba78ae 100644 --- a/src_cpp/include/py_handle_state.h +++ b/src_cpp/include/py_handle_state.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -39,6 +40,9 @@ struct PyDatabaseState { struct PyConnectionState { std::shared_ptr database; std::unique_ptr storageDriver; + // StorageDriver runs BEGIN, a read and COMMIT as separate statements on one context, so + // calls from threads that released the GIL must not overlap. + std::mutex storageMtx; std::unique_ptr conn; std::unordered_map arrowTableRefs; diff --git a/src_cpp/py_connection.cpp b/src_cpp/py_connection.cpp index c74ae26..24d431f 100644 --- a/src_cpp/py_connection.cpp +++ b/src_cpp/py_connection.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #ifndef _WIN32 @@ -18,6 +19,7 @@ #include "common/constants.h" #include "common/exception/not_implemented.h" #include "common/exception/runtime.h" +#include "common/finally_wrapper.h" #include "common/json_utils.h" #include "common/types/json_type.h" #include "common/types/uuid.h" @@ -361,41 +363,79 @@ void PyConnection::setMaxNumThreadForExec(uint64_t numThreads) { // prepare() returns. PyPreparedStatement PyConnection::prepare(const std::string& query, const py::dict& parameters) { auto& stateRef = refState(); + auto keepAlive = state; auto params = transformPythonParameters(parameters, &stateRef.ref()); - auto preparedStatement = stateRef.ref().prepareWithParams(query, std::move(params)); + std::unique_ptr preparedStatement; + { + py::gil_scoped_release release; + preparedStatement = stateRef.ref().prepareWithParams(query, std::move(params)); + } PyPreparedStatement pyPreparedStatement; pyPreparedStatement.state = std::make_shared(); - pyPreparedStatement.state->connection = state; + pyPreparedStatement.state->connection = keepAlive; pyPreparedStatement.state->preparedStatement = std::move(preparedStatement); return pyPreparedStatement; } +// Not a call_guard: the connection state is pinned before the GIL is released, as in execute(). uint64_t PyConnection::getNumNodes(const std::string& nodeName) { - return refState().storage().getNumNodes(nodeName); + auto& stateRef = refState(); + auto keepAlive = state; + py::gil_scoped_release release; + std::lock_guard lock{stateRef.storageMtx}; + return stateRef.storage().getNumNodes(nodeName); } uint64_t PyConnection::getNumRels(const std::string& relName) { - return refState().storage().getNumRels(relName); + auto& stateRef = refState(); + auto keepAlive = state; + py::gil_scoped_release release; + std::lock_guard lock{stateRef.storageMtx}; + return stateRef.storage().getNumRels(relName); } void PyConnection::getAllEdgesForTorchGeometric(py::array_t& npArray, const std::string& srcTableName, const std::string& relName, const std::string& dstTableName, size_t queryBatchSize) { auto& stateRef = refState(); + auto keepAlive = state; + auto bufferInfo = npArray.request(); + auto buffer = (int64_t*)bufferInfo.ptr; + py::gil_scoped_release release; + + uint64_t numDstNodes = 0; + uint64_t numRels = 0; + { + std::lock_guard lock{stateRef.storageMtx}; + numDstNodes = stateRef.storage().getNumNodes(dstTableName); + numRels = stateRef.storage().getNumRels(relName); + } // Get the number of nodes in the dst table for batching. - auto numDstNodes = getNumNodes(dstTableName); uint64_t batches = numDstNodes / queryBatchSize; if (numDstNodes % queryBatchSize != 0) { batches += 1; } - auto numRels = getNumRels(relName); - - auto bufferInfo = npArray.request(); - auto buffer = (int64_t*)bufferInfo.ptr; + if (bufferInfo.size < 0 || static_cast(bufferInfo.size) < 2 * numRels) { + throw RuntimeException(std::format("The edge array has {} values; {} needs {}.", + bufferInfo.size, relName, 2 * numRels)); + } + // Each batch is its own transaction, so edges committed after the count must not overflow. + uint64_t numWritten = 0; + auto claim = [&](uint64_t numEdges) { + if (numEdges > numRels - numWritten) { + throw RuntimeException(std::format( + "Relationships were added to {} while its edges were fetched.", relName)); + } + numWritten += numEdges; + }; - // Set the number of threads to 1 for fetching edges to ensure ordering. + // Each batch runs on 1 thread to keep the edges in order; the setting is repeated per batch + // since another thread can change it in between (a change landing just before the execute + // still wins). The restore runs before `release` takes the GIL back, since it waits for the + // connection. auto numThreadsForExec = stateRef.ref().getMaxNumThreadForExec(); - stateRef.ref().setMaxNumThreadForExec(1); + FinallyWrapper restoreNumThreads{ + [&] { stateRef.ref().setMaxNumThreadForExec(numThreadsForExec); }}; auto query = std::format("MATCH (a:{})-[:{}]->(b:{}) WHERE offset(id(b)) >= " "$s AND offset(id(b)) < " "$e RETURN offset(id(a)), offset(id(b))", @@ -411,6 +451,7 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t& npArray, std::unordered_map> parameters; parameters["s"] = std::make_unique(start); parameters["e"] = std::make_unique(end); + stateRef.ref().setMaxNumThreadForExec(1); auto result = stateRef.ref().executeWithParams(preparedStatement.get(), std::move(parameters)); if (!result->isSuccess()) { @@ -423,6 +464,7 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t& npArray, for (auto i = 0u; i < table.getNumTuples(); ++i) { auto tuple = table.getTuple(i); auto overflowValue = (overflow_value_t*)(tuple + tableSchema->getColOffset(1)); + claim(overflowValue->numElements); for (auto j = 0u; j < overflowValue->numElements; ++j) { srcBuffer[j] = *(int64_t*)(tuple + tableSchema->getColOffset(0)); } @@ -436,6 +478,7 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t& npArray, for (auto i = 0u; i < table.getNumTuples(); ++i) { auto tuple = table.getTuple(i); auto overflowValue = (overflow_value_t*)(tuple + tableSchema->getColOffset(0)); + claim(overflowValue->numElements); for (auto j = 0u; j < overflowValue->numElements; ++j) { srcBuffer[j] = ((int64_t*)overflowValue->value)[j]; } @@ -449,7 +492,6 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t& npArray, throw std::runtime_error("Wrong result table schema."); } } - stateRef.ref().setMaxNumThreadForExec(numThreadsForExec); } bool PyConnection::isPandasDataframe(const py::handle& object) { @@ -1196,22 +1238,28 @@ static ExportedArrowTable exportArrowTable(py::object arrowTable) { std::unique_ptr PyConnection::createArrowTable(const std::string& tableName, py::object arrowTable) { auto& stateRef = refState(); + auto keepAlive = state; py::gil_scoped_acquire acquire; auto exported = exportArrowTable(std::move(arrowTable)); - auto result = ArrowTableSupport::createViewFromArrowTable(stateRef.ref(), tableName, - std::move(exported.schema), std::move(exported.arrays)); + ArrowTableCreationResult result; + { + py::gil_scoped_release release; + result = ArrowTableSupport::createViewFromArrowTable(stateRef.ref(), tableName, + std::move(exported.schema), std::move(exported.arrays)); + } if (result.queryResult && result.queryResult->isSuccess()) { stateRef.arrowTableRefs[tableName] = std::move(exported.keepAlive); } - return checkAndWrapQueryResult(result.queryResult, state); + return checkAndWrapQueryResult(result.queryResult, keepAlive); } std::unique_ptr PyConnection::createArrowRelTable(const std::string& tableName, py::object arrowTable, const std::string& srcTableName, const std::string& dstTableName, const std::string& layout, py::object indptrTable, const std::string& dstColName) { auto& stateRef = refState(); + auto keepAliveState = state; py::gil_scoped_acquire acquire; auto layoutUpper = layout; @@ -1227,6 +1275,7 @@ std::unique_ptr PyConnection::createArrowRelTable(const std::stri if (!py::none().is(indptrTable)) { throw RuntimeException("indptr_table is only valid for CSR Arrow relationship tables"); } + py::gil_scoped_release release; result = ArrowTableSupport::createRelTableFromArrowTable(stateRef.ref(), tableName, srcTableName, dstTableName, std::move(exported.schema), std::move(exported.arrays)); } else if (layoutUpper == "CSR") { @@ -1235,6 +1284,7 @@ std::unique_ptr PyConnection::createArrowRelTable(const std::stri } auto exportedIndptr = exportArrowTable(std::move(indptrTable)); keepAlive.append(exportedIndptr.keepAlive); + py::gil_scoped_release release; result = ArrowTableSupport::createRelTableFromArrowCSR(stateRef.ref(), tableName, srcTableName, dstTableName, std::move(exported.schema), std::move(exported.arrays), std::move(exportedIndptr.schema), std::move(exportedIndptr.arrays), dstColName); @@ -1245,14 +1295,19 @@ std::unique_ptr PyConnection::createArrowRelTable(const std::stri stateRef.arrowTableRefs[tableName] = std::move(keepAlive); } - return checkAndWrapQueryResult(result.queryResult, state); + return checkAndWrapQueryResult(result.queryResult, keepAliveState); } std::unique_ptr PyConnection::dropArrowTable(const std::string& tableName) { auto& stateRef = refState(); - auto result = ArrowTableSupport::unregisterArrowTable(stateRef.ref(), tableName); + auto keepAlive = state; + std::unique_ptr result; + { + py::gil_scoped_release release; + result = ArrowTableSupport::unregisterArrowTable(stateRef.ref(), tableName); + } if (result && result->isSuccess()) { stateRef.arrowTableRefs.erase(tableName); } - return checkAndWrapQueryResult(result, state); + return checkAndWrapQueryResult(result, keepAlive); } diff --git a/test/test_gil_release.py b/test/test_gil_release.py new file mode 100644 index 0000000..5eaf3cf --- /dev/null +++ b/test/test_gil_release.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import json +import subprocess +import sys +import textwrap + +import ladybug as lb +import pytest +from type_aliases import ConnDB + +# A call that waits for the connection while holding the GIL deadlocks against a +# DataFrame scan on another thread, so each scenario runs in its own interpreter. +PRELUDE = """ +import json, threading, time +import ladybug as lb +import numpy as np +import pandas as pd +import pyarrow as pa + +db = lb.Database(":memory:") +conn = lb.Connection(db) +conn.execute("CREATE NODE TABLE person(id INT64 PRIMARY KEY)") +conn.execute("CREATE REL TABLE knows(FROM person TO person)") +conn.execute("UNWIND range(1, 3) AS i CREATE (:person {id: i})") +conn.execute("MATCH (a:person), (b:person) WHERE a.id < b.id CREATE (a)-[:knows]->(b)") +people = pa.table({"id": pa.array([1, 2, 3], pa.int64())}) +flat = pa.table({"from": pa.array([1, 2], pa.int64()), "to": pa.array([2, 3], pa.int64())}) +indices = pa.table({"to": pa.array([1, 2], pa.uint64())}) +indptr = pa.table({"indptr": pa.array([0, 1, 2, 2], pa.uint64())}) +edges = np.empty(6, dtype=np.int64) +deadline = time.monotonic() + 2 +scans, errors = 0, [] + + +def scan(): + global scans + df = pd.DataFrame({"v": np.arange(50_000, dtype=np.int64)}) + while time.monotonic() < deadline: + try: + conn.execute("LOAD FROM $df RETURN count(*)", {"df": df}).get_all() + scans += 1 + except Exception as e: + errors.append(repr(e)) +""" + +EPILOGUE = """ +scanner = threading.Thread(target=scan) +scanner.start() +calls = 0 +while time.monotonic() < deadline: + call() + calls += 1 +scanner.join() +print(json.dumps({"scans": scans, "calls": calls, "errors": errors})) +""" + +CALLS = { + "prepare": """ +# Kept until the scan stops: destroying a statement while another thread executes +# races on the engine's statement map (LadybugDB/ladybug#1718). +kept = [] + + +def call(): + kept.append(conn.prepare("RETURN $x + 1")) +""", + "create_arrow_table": """ +def call(): + conn.create_arrow_table("people", people) + conn.drop_arrow_table("people") +""", + "create_arrow_table_fails": """ +def call(): + try: + conn.create_arrow_table("person", pd.DataFrame({"id": [1, 2]})) + except RuntimeError: + return + raise AssertionError("the name is taken, so create_arrow_table must fail") +""", + "create_arrow_rel_table": """ +def call(): + conn.create_arrow_table("people", people) + conn.create_arrow_rel_table("knows_flat", flat, "people", "people") + conn.drop_arrow_table("knows_flat") + conn.drop_arrow_table("people") +""", + "create_arrow_rel_table_csr": """ +def call(): + conn.create_arrow_table("people", people) + conn.create_arrow_rel_table( + "knows_csr", indices, "people", "people", + layout=lb.ArrowRelTableLayout.CSR, indptr_dataframe=indptr, + ) + conn.drop_arrow_table("knows_csr") + conn.drop_arrow_table("people") +""", + "get_num_nodes": """ +def call(): + assert conn._connection.get_num_nodes("person") == 3 +""", + "get_num_rels": """ +def call(): + assert conn._connection.get_num_rels("knows") == 3 +""", + "get_all_edges_for_torch_geometric": """ +def call(): + conn._connection.get_all_edges_for_torch_geometric(edges, "person", "knows", "person", 2) + assert edges.tolist() == [0, 0, 1, 1, 2, 2], edges +""", +} + +# Methods of the pybind connection, used by the torch-geometric store. +PYBIND_ONLY = {"get_num_nodes", "get_num_rels", "get_all_edges_for_torch_geometric"} + + +def _using_pybind_backend() -> bool: + return lb.Database(":memory:", lazy_init=True)._use_pybind_backend + + +@pytest.mark.parametrize("call", sorted(CALLS)) +def test_call_does_not_block_a_dataframe_scan(call: str) -> None: + if call in PYBIND_ONLY and not _using_pybind_backend(): + pytest.skip(f"{call} is a pybind connection method") + script = textwrap.dedent(PRELUDE) + CALLS[call] + textwrap.dedent(EPILOGUE) + try: + proc = subprocess.run( + [sys.executable, "-W", "ignore::DeprecationWarning", "-c", script], + capture_output=True, + text=True, + timeout=60, + ) + except subprocess.TimeoutExpired: + pytest.fail(f"{call} deadlocked with a DataFrame scan on another thread") + assert proc.returncode == 0, proc.stderr[-2000:] + assert "Exception in thread" not in proc.stderr, proc.stderr[-2000:] + counts = json.loads(proc.stdout.splitlines()[-1]) + assert counts["errors"] == [], counts + assert counts["scans"] > 0, counts + assert counts["calls"] > 0, counts + + +def test_edges_for_torch_geometric_need_room_for_every_edge( + conn_db_in_mem: ConnDB, +) -> None: + if not _using_pybind_backend(): + pytest.skip("get_all_edges_for_torch_geometric is a pybind connection method") + np = pytest.importorskip("numpy") + conn, _ = conn_db_in_mem + conn.execute("CREATE NODE TABLE person(id INT64 PRIMARY KEY)") + conn.execute("CREATE REL TABLE knows(FROM person TO person)") + conn.execute("UNWIND range(1, 3) AS i CREATE (:person {id: i})") + conn.execute( + "MATCH (a:person), (b:person) WHERE a.id < b.id CREATE (a)-[:knows]->(b)" + ) + edges = np.empty(4, dtype=np.int64) + with pytest.raises( + RuntimeError, match="The edge array has 4 values; knows needs 6" + ): + conn._connection.get_all_edges_for_torch_geometric( + edges, "person", "knows", "person", 2 + ) + + +GRAPH = """ +import json, threading, time +import ladybug as lb +import numpy as np + +db = lb.Database(":memory:") +conn = lb.Connection(db) +conn.execute("CREATE NODE TABLE person(id INT64 PRIMARY KEY)") +conn.execute("CREATE REL TABLE knows(FROM person TO person)") +conn.execute("UNWIND range(0, 199) AS i CREATE (:person {id: i})") +conn.execute("MATCH (a:person), (b:person) WHERE b.id = a.id + 1 CREATE (a)-[:knows]->(b)") +""" + +# The two counts share one storage context, so they must not interleave. +COUNTS_FROM_TWO_THREADS = """ +deadline = time.monotonic() + 2 +results = [] + + +def count(method, name): + while time.monotonic() < deadline: + results.append(getattr(conn._connection, method)(name)) + + +threads = [ + threading.Thread(target=count, args=("get_num_nodes", "person")), + threading.Thread(target=count, args=("get_num_rels", "knows")), +] +for t in threads: + t.start() +for t in threads: + t.join() +print(json.dumps({"results": sorted(set(results)), "calls": len(results)})) +""" + +# Edges committed by another connection between two batches must not be written +# past the array, which is sized from the count taken before the fetch. +EDGES_WHILE_ANOTHER_CONNECTION_INSERTS = """ +writer = lb.Connection(db) +done = threading.Event() + + +def insert(): + i = 0 + while not done.is_set(): + writer.execute( + "MATCH (a:person {id: $a}), (b:person {id: $b}) CREATE (a)-[:knows]->(b)", + {"a": i % 200, "b": (i * 7) % 200}, + ) + i += 1 + + +thread = threading.Thread(target=insert) +thread.start() +deadline = time.monotonic() + 10 +fetches, added = 0, 0 +while time.monotonic() < deadline and added == 0: + edges = np.empty(2 * conn._connection.get_num_rels("knows"), dtype=np.int64) + try: + conn._connection.get_all_edges_for_torch_geometric(edges, "person", "knows", "person", 1) + except RuntimeError as e: + if "while its edges were fetched" in str(e): + added += 1 + elif "The edge array has" not in str(e): + raise + fetches += 1 +done.set() +thread.join() +print(json.dumps({"fetches": fetches, "added": added})) +""" + + +def _run(script: str) -> dict[str, object]: + proc = subprocess.run( + [sys.executable, "-c", textwrap.dedent(GRAPH) + textwrap.dedent(script)], + capture_output=True, + text=True, + timeout=60, + ) + assert proc.returncode == 0, proc.stderr[-2000:] + return json.loads(proc.stdout.splitlines()[-1]) + + +def test_counts_from_two_threads_on_one_connection() -> None: + if not _using_pybind_backend(): + pytest.skip("get_num_nodes is a pybind connection method") + counts = _run(COUNTS_FROM_TWO_THREADS) + assert counts["results"] == [199, 200], counts + assert counts["calls"] > 0, counts + + +def test_edges_for_torch_geometric_while_another_connection_inserts() -> None: + if not _using_pybind_backend(): + pytest.skip("get_all_edges_for_torch_geometric is a pybind connection method") + counts = _run(EDGES_WHILE_ANOTHER_CONNECTION_INSERTS) + assert counts["added"] == 1, counts