8000 feat(jvm): expose incoming-reference lookup on write transactions (project-minigraf/minigraf#924) by adityamukho · Pull Request #29 · project-minigraf/minigraf-java · 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 @@ -17,7 +17,7 @@ path = "src/uniffi_bindgen.rs"
[dependencies]
# Pin to the exact released version. The release workflow updates this line.
# 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 = "353bd58be48dac043fa131305f620324eacbadff" }
uniffi = { version = "0.31.1", features = ["cli"] }
thiserror = "2.0.18"
serde_json = "1.0.149"
Expand Down
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,40 @@ println(result) // {"transacted":<tx id>}
From Java, use `io.github.project_minigraf.minigraf.Minigraf.openInMemory()` / `Minigraf.open(path)`.
See [java/README.md](java/README.md) for supported platforms and Java usage.

## Incoming references (v3)

Inside a write transaction, `incomingRefs(target, maxLinks, maxRecords)` returns a
typed `IncomingRefs.Complete` or `IncomingRefs.Exhausted`:

```kotlin
db.beginWrite().use { tx ->
when (val result = tx.incomingRefs("82958a33-8334-5ef8-ae38-de39ce3fab69", 100, 10_000)) {
is IncomingRefs.Complete -> {
for (link in result.links) println("${link.source} ${link.attribute}")
// Discovery is complete; stage any deletes here, then commit.
}
is IncomingRefs.Exhausted -> {
println("Budget ${result.budget} exhausted after ${result.recordsExamined} records")
// Retry with larger budgets or abandon the delete.
}
}
}
```

Import `io.github.project_minigraf.minigraf.IncomingRefs` for this example.
`maxLinks` bounds distinct `(source, attribute)` links; `maxRecords` bounds stored
fact versions examined across all layers, including superseded and retracted
versions. Both are nonnegative `Long` counts; zero is a real limit. Each outcome
reports `recordsExamined`. Exhaustion has **no partial link list**: require
`Complete` before deleting, and distinguish it from complete-empty.

The lookup reads earlier statements in this transaction and stages nothing. It
returns only stored scalar Ref values, excluding Keywords, Strings, set members
and rule-derived facts. Valid time is ignored, so future-dated and expired
assertions are included; the newest assertion or retraction decides whether a
link is live. Source UUID strings are canonical, attributes are strings, and
result order is unspecified. See [Java usage and errors](java/README.md#incoming-references-v3).

## Building from source

Requires Rust stable toolchain and JDK 17.
Expand Down
22 changes: 22 additions & 0 deletions consumer-test/src/test/java/ContractTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import io.github.project_minigraf.minigraf.IncomingRef;
import io.github.project_minigraf.minigraf.IncomingRefBudget;
import io.github.project_minigraf.minigraf.IncomingRefs;
import io.github.project_minigraf.minigraf.MiniGrafAccumulator;
import io.github.project_minigraf.minigraf.MiniGrafDb;
import io.github.project_minigraf.minigraf.MiniGrafException;
Expand Down Expand Up @@ -173,4 +176,23 @@ void invalidDatalogThrowsMiniGrafException() throws Exception {
assertThrows(MiniGrafException.class, () -> db.execute("(query [:find"));
}
}

@Test
void incomingRefsFromPackagedJar() throws Exception {
String target = "82958a33-8334-5ef8-ae38-de39ce3fab69";
String source = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
try (MiniGrafDb db = Minigraf.openInMemory(); MiniGrafWriteTransaction tx = db.beginWrite()) {
tx.execute("(transact [[#uuid \"" + source + "\" :edge #uuid \"" + target + "\"] [:alias :edge :target]])");
IncomingRefs.Exhausted exhausted = (IncomingRefs.Exhausted) tx.incomingRefs(target, 0, 10);
assertEquals(IncomingRefBudget.LINKS, exhausted.getBudget());
assertEquals(1L, exhausted.getRecordsExamined());
IncomingRefs.Complete complete = (IncomingRefs.Complete) tx.incomingRefs(target, 1, 10);
assertEquals(1, complete.getLinks().size());
IncomingRef link = complete.getLinks().get(0);
assertTrue(source.equals(link.getSource()), "canonical source UUID");
assertEquals(":edge", link.getAttribute());
assertEquals(1L, complete.getRecordsExamined());
tx.commit();
}
}
}
57 changes: 53 additions & 4 deletions java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,8 @@ db.registerAggregate("product", () -> new MiniGrafAccumulator() {

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
`353bd58b`), which also provides incoming references.

```kotlin
val db = MiniGrafDb.open("bank.graph")
Expand Down Expand Up @@ -303,20 +303,69 @@ try (MiniGrafWriteTransaction tx = db.beginWriteWith(Minigraf.txOptions().chunkF
`{"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 it is finished: `execute` and `commit` then
`tx.rollback()` discards it. Either way it is finished: `execute`, `incomingRefs` and `commit` then
throw API-018, and `rollback` does nothing.
- Commit is always explicit. `close()` (and `use { }`, try-with-resources) frees the transaction
and rolls it back unless it committed; after `close()` the object cannot be used. The
garbage collector may never free an abandoned one, so do not rely on it.
- An open transaction holds the database's write lock until it finishes, so end every
transaction explicitly or through `use { }` or try-with-resources. On the thread that began it, database
calls (`execute`, `query`, `prepare`, `factLog`, `checkpoint`, another `beginWrite`, prepared queries) fail with INT-001, and so do user functions its statements run. A user function that calls the transaction it runs in (`execute`, `commit`, `rollback`) gets INT-001 too. On
calls (`execute`, `query`, `prepare`, `factLog`, `checkpoint`, another `beginWrite`, prepared queries) fail with INT-001, and so do user functions its statements run. A user function that calls the transaction it runs in (`execute`, `incomingRefs`, `commit`, `rollback`) gets INT-001 too. On
other threads, writes and begins wait until it ends; 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 the database waits on that transaction.
- Rules registered inside a transaction stay registered after a rollback.
- The transaction keeps its database open until it is closed.

### Incoming references (v3)

`tx.incomingRefs(target: String, maxLinks: Long, maxRecords: Long)` discovers all
live incoming scalar references in the current write view, including earlier
statements in the transaction. It stages nothing and may be retried after either
outcome. Require `IncomingRefs.Complete` before staging deletes. Exhaustion has
**no partial link list**, and is distinct from a complete result with no links.

```java
try (MiniGrafWriteTransaction tx = db.beginWrite()) {
IncomingRefs result = tx.incomingRefs("82958a33-8334-5ef8-ae38-de39ce3fab69", 100L, 10_000L);
if (result instanceof IncomingRefs.Complete) {
IncomingRefs.Complete complete = (IncomingRefs.Complete) result;
for (IncomingRef link : complete.getLinks()) {
String source = link.getSource(); // canonical UUID string
String attribute = link.getAttribute();
// Use the complete set to plan any deletes in this transaction.
}
long examined = complete.getRecordsExamined();
} else if (result instanceof IncomingRefs.Exhausted) {
IncomingRefs.Exhausted exhausted = (IncomingRefs.Exhausted) result;
IncomingRefBudget budget = exhausted.getBudget(); // LINKS or RECORDS
long examined = exhausted.getRecordsExamined();
// Retry with larger budgets or abandon the delete.
}
}
```

Use `import io.github.project_minigraf.minigraf.*;` for these types. Kotlin uses
`when (result)` with `is IncomingRefs.Complete` / `is IncomingRefs.Exhausted`, and
properties `links`, `s BD0 ource`, `attribute`, `budget`, and `recordsExamined`.

- `maxLinks` caps distinct `(source, attribute)` pairs in a complete result.
`maxRecords` caps stored fact versions examined across all layers, including
superseded versions, retractions and lookahead. `recordsExamined` never exceeds
`maxRecords`, but may differ before and after a checkpoint for the same links.
- Both budgets are nonnegative `Long` counts, and zero is a real limit. A zero
records budget can complete empty only when no record needs inspection. Limits
do not reserve memory up front. Result order is unspecified.
- Only stored top-level Ref values count: Keywords (even aliases of the target),
Strings, references inside sets and rule-derived facts are excluded. The newest
assertion or retraction determines whether a link is live. Valid time is
ignored: future-dated and expired assertions are included.
- An unknown target completes with no links. Invalid UUIDs, negative budgets and
counts that cannot fit the native platform are API-017. A committed or rolled
back transaction is API-018, checked before arguments. Callback reentry is
INT-001, checked before locking or validation, so it cannot block on itself.
Storage and decoding failures remain errors, never complete-empty or exhausted.

## Links

- [Full Java/JVM integration guide](https://github.com/project-minigraf/minigraf/wiki/Use-Cases#java--jvm)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
Expand Down Expand Up @@ -154,4 +157,108 @@ void writeTransactionFromJava() throws Exception {
assertTrue(all.contains("Bob"), all);
assertFalse(all.contains("Carol"), "try-with-resources rolls back unless committed");
}

private static final String TARGET = "82958a33-8334-5ef8-ae38-de39ce3fab69";
private static final String SOURCE = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
private static final String INCOMING = "(transact [[#uuid \"" + SOURCE + "\" :edge #uuid \"" + TARGET
+ "\"] [#uuid \"" + SOURCE + "\" :other #uuid \"" + TARGET + "\"] [:alias :edge :target]])";

private static void assertIncoming(MiniGrafWriteTransaction tx) throws Exception {
IncomingRefs result = tx.incomingRefs(TARGET.toUpperCase(java.util.Locale.ROOT), Long.MAX_VALUE, Long.MAX_VALUE);
assertTrue(result instanceof IncomingRefs.Complete);
IncomingRefs.Complete complete = (IncomingRefs.Complete) result;
assertEquals(2, complete.getLinks().size());
Set<String> attributes = new java.util.HashSet<>();
for (IncomingRef link : complete.getLinks()) {
assertTrue(SOURCE.equals(link.getSource()), "canonical source UUID");
attributes.add(link.getAttribute());
}
assertEquals(Set.of(":edge", ":other"), attributes);
assertTrue(complete.getRecordsExamined() >= 2);
}

@Test
void incomingRefsTypedOutcomesAndRetryFromJava() throws Exception {
try (MiniGrafDb db = Minigraf.openInMemory(); MiniGrafWriteTransaction tx = db.beginWrite()) {
IncomingRefs.Complete empty = (IncomingRefs.Complete) tx.incomingRefs(TARGET, 0, 0);
assertTrue(empty.getLinks().isEmpty());
assertEquals(0L, empty.getRecordsExamined());
tx.execute(INCOMING);
assertIncoming(tx); // A same-spelling Keyword is excluded.
IncomingRefs.Exhausted links = (IncomingRefs.Exhausted) tx.incomingRefs(TARGET, 1, 100);
assertEquals(IncomingRefBudget.LINKS, links.getBudget());
assertTrue(links.getRecordsExamined() >= 2 && links.getRecordsExamined() <= 100);
IncomingRefs.Exhausted records = (IncomingRefs.Exhausted) tx.incomingRefs(TARGET, 2, 1);
assertEquals(IncomingRefBudget.RECORDS, records.getBudget());
assertEquals(1L, records.getRecordsExamined());
assertIncoming(tx);
}
}

@Test
void incomingRefsCommitReopenRollbackAndFinishedFromJava() throws Exception {
String path = dir.resolve("incoming.graph").toString();
try (MiniGrafDb db = Minigraf.open(path)) {
try (MiniGrafWriteTransaction tx = db.beginWrite()) {
tx.execute(INCOMING);
assertIncoming(tx);
tx.commit();
MiniGrafException e = assertThrows(MiniGrafException.Api.class, () -> tx.incomingRefs(TARGET, 2, 100));
assertTrue(Minigraf.errorMessage(e).startsWith("[API-018]"));
}
db.checkpoint();
}
try (MiniGrafDb db = Minigraf.open(path)) {
try (MiniGrafWriteTransaction tx = db.beginWrite()) {
assertIncoming(tx);
tx.execute("(retract [[#uuid \"" + SOURCE + "\" :edge #uuid \"" + TARGET + "\"]])");
IncomingRefs.Complete remaining = (IncomingRefs.Complete) tx.incomingRefs(TARGET, 2, 100);
assertEquals(1, remaining.getLinks().size());
assertEquals(":other", remaining.getLinks().get(0).getAttribute());
tx.rollback();
MiniGrafException e = assertThrows(MiniGrafException.Api.class, () -> tx.incomingRefs("invalid", -1, -1));
assertTrue(Minigraf.errorMessage(e).startsWith("[API-018]"));
}
try (MiniGrafWriteTransaction tx = db.beginWrite()) {
assertIncoming(tx);
}
}
}

@Test
void incomingRefsInvalidArgumentsFromJava() throws Exception {
try (MiniGrafDb db = Minigraf.openInMemory(); MiniGrafWriteTransaction tx = db.beginWrite()) {
for (long[] budgets : new long[][] {{-1, 1}, {1, -1}}) {
MiniGrafException e = assertThrows(MiniGrafException.Api.class,
() -> tx.incomingRefs(TARGET, budgets[0], budgets[1]));
assertTrue(Minigraf.errorMessage(e).startsWith("[API-017]"));
}
MiniGrafException e = assertThrows(MiniGrafException.Api.class, () -> tx.incomingRefs("invalid", 1, 1));
assertTrue(Minigraf.errorMessage(e).startsWith("[API-017]"));
assertTrue(tx.isOpen());
}
}

@Test
void incomingRefsCallbackReentryFromJava() {
assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
try (MiniGrafDb db = Minigraf.openInMemory()) {
db.execute("(transact [[:a :n 1]])");
try (MiniGrafWriteTransaction tx = db.beginWrite()) {
List<String> seen = new ArrayList<>();
db.registerPredicate("incoming?", v -> {
for (String target : List.of(TARGET, "invalid")) {
MiniGrafException e = assertThrows(MiniGrafException.Other.class,
() -> tx.incomingRefs(target, target.equals(TARGET) ? 2 : -1, 100));
seen.add(Minigraf.errorMessage(e).substring(1, 8));
}
return true;
});
tx.execute("(query [:find ?n :where [?e :n ?n] [(incoming? ?n)]])");
assertEquals(List.of("INT-001", "INT-001"), seen);
tx.commit();
}
}
});
}
}
Loading
Loading
0