Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src_cpp/include/py_handle_state.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#pragma once

#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>

Expand Down Expand Up @@ -39,6 +40,9 @@ struct PyDatabaseState {
struct PyConnectionState {
std::shared_ptr<PyDatabaseState> database;
std::unique_ptr<lbug::main::StorageDriver> 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<lbug::main::Connection> conn;
std::unordered_map<std::string, py::object> arrowTableRefs;

Expand Down
91 changes: 73 additions & 18 deletions src_cpp/py_connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <algorithm>
#include <atomic>
#include <cctype>
#include <mutex>
#include <utility>

#ifndef _WIN32
Expand All @@ -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"
Expand Down Expand Up @@ -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<main::PreparedStatement> preparedStatement;
{
py::gil_scoped_release release;
preparedStatement = stateRef.ref().prepareWithParams(query, std::move(params));
}
PyPreparedStatement pyPreparedStatement;
pyPreparedStatement.state = std::make_shared<PyPreparedStatementState>();
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<int64_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<uint64_t>(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))",
Expand All @@ -411,6 +451,7 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t<int64_t>& npArray,
std::unordered_map<std::string, std::unique_ptr<Value>> parameters;
parameters["s"] = std::make_unique<Value>(start);
parameters["e"] = std::make_unique<Value>(end);
stateRef.ref().setMaxNumThreadForExec(1);
auto result =
stateRef.ref().executeWithParams(preparedStatement.get(), std::move(parameters));
if (!result->isSuccess()) {
Expand All @@ -423,6 +464,7 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t<int64_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));
}
Expand All @@ -436,6 +478,7 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t<int64_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];
}
Expand All @@ -449,7 +492,6 @@ void PyConnection::getAllEdgesForTorchGeometric(py::array_t<int64_t>& npArray,
throw std::runtime_error("Wrong result table schema.");
}
}
stateRef.ref().setMaxNumThreadForExec(numThreadsForExec);
}

bool PyConnection::isPandasDataframe(const py::handle& object) {
Expand Down Expand Up @@ -1196,22 +1238,28 @@ static ExportedArrowTable exportArrowTable(py::object arrowTable) {
std::unique_ptr<PyQueryResult> 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<PyQueryResult> 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;
Expand All @@ -1227,6 +1275,7 @@ std::unique_ptr<PyQueryResult> 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") {
Expand All @@ -1235,6 +1284,7 @@ std::unique_ptr<PyQueryResult> 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);
Expand All @@ -1245,14 +1295,19 @@ std::unique_ptr<PyQueryResult> PyConnection::createArrowRelTable(const std::stri
stateRef.arrowTableRefs[tableName] = std::move(keepAlive);
}

return checkAndWrapQueryResult(result.queryResult, state);
return checkAndWrapQueryResult(result.queryResult, keepAliveState);
}

std::unique_ptr<PyQueryResult> PyConnection::dropArrowTable(const std::string& tableName) {
auto& stateRef = refState();
auto result = ArrowTableSupport::unregisterArrowTable(stateRef.ref(), tableName);
auto keepAlive = state;
std::unique_ptr<QueryResult> 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);
}
Loading
Loading