8000 feat: expose the incoming-reference lookup on write transactions (project-minigraf/minigraf#925) by adityamukho · Pull Request #23 · project-minigraf/minigraf-python · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
22 changes: 1 addition & 21 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ path = "src/uniffi_bindgen.rs"

[dependencies]
# Unreleased v3 core (format v8). Switches to minigraf = "=3.0.0" at the v3.0.0 release.
minigraf = { git = "https://github.com/project-minigraf/minigraf", rev = "32d71ce013a5af0748185fa69403d9151ba94453" }
minigraf = { git = "https://github.com/project-minigraf/minigraf", rev = "b6245cc2c6f75d5493bd0d05673477414990c72f" }
uniffi = { version = "0.31.1", features = ["cli"] }
thiserror = "2.0.18"
serde_json = "1.0.149"
Expand Down
60 changes: 56 additions & 4 deletions README.md
< 8000 td id="diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R210" data-line-number="210" class="blob-num blob-num-context js-linkable-line-number js-blob-rnum">
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,8 @@ db.execute("(query [:find ?a (product ?a :over (:order-by ?a)) :where [?e :age ?

A write transaction stages several `transact`, `retract` and `query` statements, with
queries seeing what it staged, and then commits them as one transaction or rolls them
back (minigraf#824). First in the release built on core v3.0.0 (core commit
`32d71ce0`).
back (minigraf#824). Available in the pinned, unreleased v3 core (commit
`b6245cc2`), which also provides incoming references.

```python
import json
Expand All @@ -232,21 +232,73 @@ with db.begin_write() as tx:
`{"ok": true}`. A statement that fails stages nothing and leaves the transaction open.
There are no cursors or prepared queries inside a transaction.
- `tx.commit()` applies everything as one transaction; a commit that fails rolls back.
`tx.rollback()` discards it. Either way the transaction is finished: `execute` and
`tx.rollback()` discards it. Either way the transaction is finished: `execute`, `incoming_refs` and
`commit` then raise API-018, and `rollback` does nothing.
- Commit is always explicit: leaving the `with` block, or the transaction being garbage
collected, rolls back. Python may collect it late, so end every transaction with
`commit()`, `rollback()` or a `with` block.
- An open transaction holds the database's write lock. On the thread that began it,
database calls (`execute`, `query`, `prepare`, `fact_log`, `checkpoint`, another
`begin_write`, prepared queries) raise INT-001; so do user functions it runs. A user function that
calls the transaction it runs in (`execute`, `commit`, `rollback`) gets INT-001 too. On other
calls the transaction it runs in (`execute`, `incoming_refs`, `commit`, `rollback`) gets INT-001 too. On other
threads, writes and `begin_write` wait until it ends, and queries read the committed
state. Use a transaction on the thread that began it: a thread that uses one it did
not begin and then writes through `db` waits on that transaction.
- Rules registered inside a transaction stay registered after a rollback.
- The transaction keeps its database open until it is freed.

### Incoming references (v3)

`tx.incoming_refs(target: str, max_links: int, max_records: int) -> IncomingRefs`
works on `begin_write()`'s transaction both inside and outside `with`. The public
`minigraf` package exports `IncomingRef`, `IncomingRefBudget` and `IncomingRefs`.

```python
from minigraf import IncomingRefs, IncomingRefBudget

with db.begin_write() as tx:
result = tx.incoming_refs("82958a33-8334-5ef8-ae38-de39ce3fab69", 100, 10_000)
if isinstance(result, IncomingRefs.COMPLETE):
links = [(link.source, link.attribute) for link in result.links]
examined = result.records_examined
# Plan any deletes using the complete set, then stage and commit them.
elif isinstance(result, IncomingRefs.EXHAUSTED):
budget = result.budget # IncomingRefBudget.LINKS or .RECORDS
examined = result.records_examined
# Retry with larger budgets or abandon the delete.
```

The lookup reads the current write view, including earlier staged statements, and
stages nothing. A complete result contains `IncomingRef` records with canonical
lowercase UUID `source` strings and `attribute` strings; order is unspecified.
Complete-empty is distinct from exhaustion, which has **no partial link list**.
Require complete before deleting: run discovery before staging deletes, and retry
with larger budgets or abandon on exhausted. **Exhaustion does not undo earlier
staged writes**; an explicit commit still commits them.

- Both budgets are mandatory exact caps, with no unlimited sentinel. The accepted
range is `0..=min(i64::MAX, usize::MAX)`: `2^63-1` on 64-bit targets and `2^32-1`
on 32-bit targets (including Android's 32-bit ABIs). Zero is a real limit;
`0, 0` completes empty only when no record needs inspection. Large budgets do
not allocate proportional memory up front.
- The links budget caps distinct `(source, attribute)` pairs. The records budget
caps fact versions examined across all layers, including superseded versions,
retractions and lookahead. The returned record count never exceeds that budget;
checkpointing can change the count without changing the links.
- Only stored scalar Ref values count. Keywords (even an alias of the target),
UUID-looking Strings, refs inside sets and rule-derived facts are excluded.
Valid time is ignored: future and expired assertions count. The newest assertion
or retraction decides whether a link is live.
- Invalid UUIDs and negative or unrepresentable budgets give `API-017`. A finished
transaction gives `API-018` before argument validation. A callback reentering its
own transaction gives `INT-001` before locking or validation. Storage and decoding
errors remain errors. Complete, exhausted and `API-017` leave the transaction
open for further statements, retry, commit or rollback.

Python integers outside the signed 64-bit range also raise `MiniGrafError` with
`[API-017]`, preserving finished/reentrant precedence. Wrong Python types may
raise `TypeError`.

## Fact log and log writer

`db.fact_log(filter)` streams every fact version (assertions and retractions, with
Expand Down
93 changes: 93 additions & 0 deletions consumer-test/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import minigraf
from minigraf import Accumulator, Aggregate, MiniGrafDb, MiniGrafError, Predicate, UdfError, Value
from minigraf import IncomingRef, IncomingRefBudget, IncomingRefs

QUERY = "(query [:find ?n :where [?e :name ?n]])"

Expand Down Expand Up @@ -158,3 +159,95 @@ def finish(self, count):
del tx, txdb
assert sorted(names(minigraf.open(tx_path))) == ["Alice", "Bob"], "the commit survives reopen"
print("ok: write transactions commit, roll back and survive reopen")

# minigraf#925: typed incoming references and Python integer boundaries.
assert all(name in minigraf.__all__ for name in ("IncomingRef", "IncomingRefBudget", "IncomingRefs"))
target = "82958a33-8334-5ef8-ae38-de39ce3fab69"
source = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
setup = f'''(transact [[#uuid "{source}" :edge #uuid "{target}"]
[#uuid "{source}" :other #uuid "{target}"] [:alias :edge :target]])'''


def complete(tx):
result = tx.incoming_refs(target.upper(), 2, 100)
assert isinstance(result, IncomingRefs.COMPLETE)
assert result.records_examined <= 100
assert all(isinstance(link, IncomingRef) for link in result.links)
return {(link.source, link.attribute) for link in result.links}


def expect_code(expected, call):
try:
call()
except MiniGrafError as error:
assert error.msg.startswith(f"[{expected}]")
else:
raise AssertionError(f"expected {expected}")


def invalid_calls(tx, target):
yield lambda: tx.incoming_refs("invalid", 2, 100)
for n in (-1, 2**63, -(2**63) - 1):
for links, records in ((n, 100), (2, n)):
yield lambda links=links, records=records: tx.incoming_refs(target, links, records)
yield lambda links=links, records=records: tx.incoming_refs(
target=target, max_links=links, max_records=records
)


incoming = MiniGrafDb.open_in_memory()
tx = incoming.begin_write()
empty = tx.incoming_refs(target, 0, 0)
assert isinstance(empty, IncomingRefs.COMPLETE) and empty.links == [] and empty.records_examined == 0
for call in invalid_calls(tx, target):
expect_code("API-017", call)
tx.execute(setup)
for links, records, budget in ((1, 100, IncomingRefBudget.LINKS), (2, 1, IncomingRefBudget.RECORDS)):
result = tx.incoming_refs(target, links, records)
assert isinstance(result, IncomingRefs.EXHAUSTED) and result.budget == budget
assert result.records_examined <= records and not hasattr(result, "links")
assert complete(tx) == {(source, ":edge"), (source, ":other")}
tx.rollback()
for call in invalid_calls(tx, "invalid"):
expect_code("API-018", call)
with incoming.begin_write() as tx:
assert tx.incoming_refs(target, 0, 0).links == []

incoming_path = os.path.join(sys.argv[1], "incoming.graph")
incoming = minigraf.open(incoming_path)
with incoming.begin_write() as tx:
tx.execute(setup)
tx.commit()
expect_code("API-018", lambda: tx.incoming_refs(target, 2, 100))
del tx, incoming
incoming = minigraf.open(incoming_path)
with incoming.begin_write() as tx:
assert complete(tx) == {(source, ":edge"), (source, ":other")}
tx.execute(f'(retract [[#uuid "{source}" :edge #uuid "{target}"]])')
assert complete(tx) == {(source, ":other")}
with incoming.begin_write() as tx:
assert complete(tx) == {(source, ":edge"), (source, ":other")}

seen = []


class IncomingCallsItsTx(Predicate):
def __init__(self, tx):
self.tx = tx

def test(self, value):
expect_code("INT-001", lambda: self.tx.incoming_refs(target, 2, 100))
for call in invalid_calls(self.tx, "invalid"):
expect_code("INT-001", call)
seen.append(True)
return True


with incoming.begin_write() as tx:
incoming.register_predicate("incoming?", IncomingCallsItsTx(tx))
tx.execute('(transact [[:probe :n 1]])')
tx.execute('(query [:find ?n :where [?e :n ?n] [(incoming? ?n)]])')
assert seen == [True]
assert complete(tx) == {(source, ":edge"), (source, ":other")}
tx.commit()
print("ok: incoming references, retry, reopen, rollback and error precedence")
25 changes: 25 additions & 0 deletions minigraf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
FactFilter,
FactOrder,
FactRecord,
IncomingRef,
IncomingRefBudget,
IncomingRefs,
MiniGrafAccumulator,
MiniGrafAggregate,
MiniGrafCursor,
Expand Down Expand Up @@ -207,6 +210,7 @@ def _query(self, bindings=None, /, **kwargs):
# ─── Write transactions (minigraf#824) ───────────────────────────────────────

_begin_write_with = MiniGrafDb.begin_write_with
_incoming_refs = MiniGrafWriteTransaction.incoming_refs


def _begin_write(self, *, synchronous=None, chunk_facts=None):
Expand All @@ -228,13 +232,31 @@ def _begin_write(self, *, synchronous=None, chunk_facts=None):
)


def _incoming_budget(value):
# Let Rust reject out-of-i64 integers after its reentry and finished checks.
if isinstance(value, int) and not _I64_MIN <= value <= _I64_MAX:
return -1
return value


def _tx_incoming_refs(self, target, max_links, max_records):
"""Discover scalar references with two exact budgets; require COMPLETE before
deleting. EXHAUSTED has no partial links and leaves earlier writes staged.
Invalid budgets are API-017, after reentry (INT-001) and finished (API-018).
"""
return _incoming_refs(
self, target, _incoming_budget(max_links), _incoming_budget(max_records)
)


def _tx_exit(self, *exc):
"""Roll back unless committed; never commits on its own."""
self.rollback()
return False


MiniGrafDb.begin_write = _begin_write
MiniGrafWriteTransaction.incoming_refs = _tx_incoming_refs


def _close_on_exit(self, *exc):
Expand Down Expand Up @@ -297,6 +319,9 @@ def _writer_exit(self, exc_type, exc, tb):
"FactLog",
"FactOrder",
"FactRecord",
"IncomingRef",
"IncomingRefBudget",
"IncomingRefs",
"LogWriter",
"MiniGrafAccumulator",
"MiniGrafAggregate",
Expand Down
Loading
Loading
0