8000 feat: override list, open options and prepared limit setters (minigraf#872) by adityamukho · Pull Request #22 · 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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, ubuntu-24.04-arm, macos-14, windows-latest]
os: [ubuntu-latest, ubuntu-24.04-arm, macos-15, windows-latest]
steps:
- uses: actions/checkout@v4
with:
Expand Down Expand Up @@ -131,7 +131,7 @@ jobs:
include:
- { name: linux-x86_64, os: ubuntu-latest, java: '17', distribution: temurin }
- { name: linux-aarch64, os: ubuntu-24.04-arm, java: '17', distribution: temurin }
- { name: macos, os: macos-14, java: '17', distribution: temurin }
- { name: macos, os: macos-15, java: '17', distribution: temurin }
- { name: windows-x86_64, os: windows-latest, java: '17', distribution: temurin }
# Temurin has no Windows arm64 build of 17.
- { name: windows-aarch64, os: windows-11-arm, java: '17', distribution: microsoft }
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ jobs:
zig-target: aarch64-unknown-linux-musl
native-dir: linux-musl/aarch64
lib-name: libminigraf_ffi.so
- os: macos-14
- os: macos-15
target: universal2
native-dir: macos/universal
lib-name: libminigraf_ffi.dylib
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/verify-published.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ jobs:
include:
- { name: linux-x86_64, os: ubuntu-latest, java: '17', distribution: temurin }
- { name: linux-aarch64, os: ubuntu-24.04-arm, java: '17', distribution: temurin }
- { name: macos, os: macos-14, java: '17', distribution: temurin }
- { name: macos, os: macos-15, java: '17', distribution: temurin }
- { name: windows-x86_64, os: windows-latest, java: '17', distribution: temurin }
- { name: windows-aarch64, os: windows-11-arm, java: '17', distribution: microsoft }
- { name: alpine, os: ubuntu-latest, container: 'eclipse-temurin:17-jdk-alpine' }
Expand Down
2 changes: 1 addition & 1 deletion 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
10000
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 = "02243f1656eedd987611a9babdfee4a8c6e22b6b" }
minigraf = { git = "https://github.com/project-minigraf/minigraf", rev = "d9755c02d19a1538ca03fd0b80c56a752bbc6504" }
uniffi = { version = "0.31.1", features = ["cli"] }
thiserror = "2.0.18"
serde_json = "1.0.149"
Expand Down
32 changes: 32 additions & 0 deletions consumer-test/src/test/java/ContractTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// The consumer contract every binding checks (spec §4), from Java: in memory,
// file-backed across a reopen, and the error type for invalid Datalog.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

Expand All @@ -9,8 +10,10 @@
import io.github.project_minigraf.minigraf.MiniGrafPreparedQuery;
import io.github.project_minigraf.minigraf.MiniGrafValue;
import io.github.project_minigraf.minigraf.Minigraf;
import io.github.project_minigraf.minigraf.Overridable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -102,6 +105,35 @@ public MiniGrafValue finish(long count) {
}
}

// minigraf#872: the override list, the new open options and a prepared setter.
@Test
void overridesOptionsAndSetters() throws Exception {
assertEquals(
List.of(Overridable.MAX_DERIVED_FACTS, Overridable.MAX_RESULTS, Overridable.MAX_ITERATIONS),
Minigraf.OVERRIDABLE_DEFAULTS,
"the default override list comes from core");
Path dir = Files.createTempDirectory("minigraf-overrides");
String path = dir.resolve("o.graph").toString();
try (MiniGrafDb db = Minigraf.openWithOptions(path, Minigraf.options()
.allowOverrides()
.transactionChunkFacts(2)
.maxIterations(1000)
.build())) {
db.execute("(transact [[:a :edge :b] [:b :edge :c] [:c :edge :d]])");
db.execute("(rule [(reach ?x ?y) [?x :edge ?y]])");
db.execute("(rule [(reach ?x ?y) [?x :edge ?z] (reach ?z ?y)])");
MiniGrafException refused = assertThrows(MiniGrafException.Api.class,
() -> db.execute("(query [:find ?x ?y :where (reach ?x ?y) :max-derived-facts 10])"));
assertTrue(Minigraf.errorMessage(refused).startsWith("[API-025]"), "an empty list refuses the keyword");
MiniGrafPreparedQuery pq = db.prepare("(query [:find ?x ?y :where (reach ?x ?y)])");
MiniGrafPreparedQuery derived = pq.withMaxIterations(1);
MiniGrafException limited = assertThrows(MiniGrafException.class,
() -> Minigraf.execute(derived, Map.of()));
assertTrue(Minigraf.errorMessage(limited).startsWith("[INT-020]"), "the derived query has its own limit");
assertTrue(Minigraf.execute(pq, Map.of()).contains("\"results\":[["), "the receiver is unchanged");
}
}

@Test
void invalidDatalogThrowsMiniGrafException() throws Exception {
try (MiniGrafDb db = Minigraf.openInMemory()) {
Expand Down
35 changes: 35 additions & 0 deletions java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,28 @@ distinct sets, aggregate groups, window rows, rule-derived facts). A query that
hold more fails with QRY-012 and frees what it held. The default, and `Long.MAX_VALUE`,
is no limit. Rows a cursor returns are not counted, so read a large answer with `query()`.

Query text may override some settings with keywords such as `:max-derived-facts 1000`.
`allowOverrides(...)` lists the `Overridable` keywords it may use (`MAX_DERIVED_FACTS`,
`MAX_RESULTS`, `QUERY_MEMORY_LIMIT`, `MAX_ITERATIONS`). Not calling it keeps the defaults,
`Minigraf.OVERRIDABLE_DEFAULTS`, read from the core library (today `MAX_DERIVED_FACTS`,
`MAX_RESULTS` and `MAX_ITERATIONS`). A list replaces the defaults, it does not add to them,
and `allowOverrides()` with no arguments refuses every keyword: a query that uses one
throws `MiniGrafException.Api` with `[API-025]` from `execute`, `query` and `prepare`.

```java
List<Overridable> allowed = new ArrayList<>(Minigraf.OVERRIDABLE_DEFAULTS);
allowed.add(Overridable.QUERY_MEMORY_LIMIT); // the defaults plus :query-memory-limit
MiniGrafDb db = Minigraf.openWithOptions("app.graph", Minigraf.options()
.allowOverrides(allowed)
.maxIterations(10_000) // rounds per stratum of a rule query, else INT-020
.transactionChunkFacts(16_384) // facts staged before a large transaction is chunked
.build());
```

`maxIterations` defaults to 1,000,000 and `Long.MAX_VALUE` is no limit;
`transactionChunkFacts` defaults to 65,536 and is clamped to 1..=1,000,000. A negative
count is `[API-017]`.

Kotlin callers can use `cursor.batches()` and `log.records()` directly, and the
generated constructors with named arguments (`OpenOptions(readOnly = true)`).

Expand Down Expand Up @@ -162,6 +184,19 @@ values come back as JSON arrays from `execute` and as `MiniGrafValue.Set` in fac
Errors are `MiniGrafException.Parse`, `.Query`, `.Storage`, `.Api` (a bad argument, a
closed object, a bind mistake) or `.Other`.

`withMaxDerivedFacts(n)`, `withQueryMemoryLimit(bytes)` and `withMaxIterations(n)` each
return a new prepared query with that limit; the one they are called on is unchanged.
They are application code, so `allowOverrides` does not apply to them, and an allowed
keyword in the query text still overrides them. `Long.MAX_VALUE` means no limit and a
negative value is `[API-017]`. A derived query keeps its database open, as any prepared
query does.

```java
MiniGrafPreparedQuery reach = db.prepare("(query [:find ?x ?y :where (reach ?x ?y)])");
MiniGrafPreparedQuery small = reach.withMaxDerivedFacts(10_000).withQueryMemoryLimit(16 << 20);
Minigraf.execute(small, Map.of()); // INT-020 or QRY-012 past a limit; reach is unchanged
```

## User functions

A predicate implements `MiniGrafPredicate` (`test(value): Boolean`) and is called in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ object Minigraf {
*/
const val WAL_CHECKPOINT_NEVER: Long = Long.MAX_VALUE

/**
* The override list that applies when [OpenOptionsBuilder.allowOverrides] is not
* called: the Rust `Overridable::DEFAULTS`, read from the core library.
*/
@JvmField
val OVERRIDABLE_DEFAULTS: List<Overridable> = overridableDefaults()

/** Opens (or creates) a file-backed database at [path]. */
@JvmStatic
@Throws(MiniGrafException::class)
Expand Down Expand Up @@ -164,6 +171,22 @@ class OpenOptionsBuilder internal constructor() {
* QRY-012. `Long.MAX_VALUE` means no limit, the default.
*/
fun queryMemoryLimit(bytes: Long) = apply { options = options.copy(queryMemoryLimit = bytes) }
/**
* The query keywords query text may use to override these settings. It replaces
* [Minigraf.OVERRIDABLE_DEFAULTS]; with no arguments it refuses them all (API-025).
* Not calling it keeps the defaults.
*/
fun allowOverrides(vararg keywords: Overridable) = allowOverrides(keywords.asList())
/** [allowOverrides] from a collection, such as [Minigraf.OVERRIDABLE_DEFAULTS]. */
fun allowOverrides(keywords: Collection<Overridable>) =
apply { options = options.copy(allowOverrides = keywords.toList()) }
/** Facts a transaction stages before a file database writes them in chunks. */
fun transactionChunkFacts(n: Long) = apply { options = options.copy(transactionChunkFacts = n) }
/**
* Rounds one stratum of a rule query may run; more fail with INT-020.
* `Long.MAX_VALUE` means no limit.
*/
fun maxIterations(n: Long) = apply { options = options.copy(maxIterations = n) }
fun build(): OpenOptions = options
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package io.github.project_minigraf.minigraf

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import kotlin.test.assertEquals
import kotlin.test.assertTrue

private val mapper = jacksonObjectMapper()

/** Override list, transactionChunkFacts and maxIterations, and the prepared limit setters (minigraf#872). */
class OverridesTest {
@TempDir
lateinit var dir: Path

private val reach = "(query [:find ?x ?y :where (reach ?x ?y)])"
private val grouped = "(query [:find ?v (count ?e) :where [?e :v ?v]])"
private val derivedKeyword = "(query [:find ?x ?y :where (reach ?x ?y) :max-derived-facts 100])"
private val memoryKeyword = "(query [:find ?x ?y :where (reach ?x ?y) :query-memory-limit 1000000])"

private fun rows(s: String): Int =
(mapper.readValue<Map<String, Any>>(s)["results"] as List<*>).size

private fun code(e: MiniGrafException): String = e.text.substring(1, 8)

private fun reachDb(name: String, options: OpenOptionsBuilder = Minigraf.options()): MiniGrafDb {
val db = Minigraf.openWithOptions(dir.resolve("$name.graph").toString(), options.build())
db.execute(
"(transact [[:a :edge :b] [:b :edge :c] [:c :edge :d] [:d :edge :e]" +
" [:p :v 1] [:q :v 1] [:r :v 2]])",
)
db.execute("(rule [(reach ?x ?y) [?x :edge ?y]])")
db.execute("(rule [(reach ?x ?y) [?x :edge ?z] (reach ?z ?y)])")
return db
}

@Test
fun defaultsAreReadFromCore() {
assertEquals(
listOf(Overridable.MAX_DERIVED_FACTS, Overridable.MAX_RESULTS, Overridable.MAX_ITERATIONS),
Minigraf.OVERRIDABLE_DEFAULTS,
)
}

@Test
fun allowOverridesReplacesTheDefaults() {
val cases = listOf(
Triple("absent", Minigraf.options(), true to false),
Triple("defaults", Minigraf.options().allowOverrides(Minigraf.OVERRIDABLE_DEFAULTS), true to false),
Triple("empty", Minigraf.options().allowOverrides(), false to false),
Triple(
"memory",
Minigraf.options().allowOverrides(Overridable.QUERY_MEMORY_LIMIT, Overridable.QUERY_MEMORY_LIMIT),
false to true,
),
Triple("all", Minigraf.options().allowOverrides(Overridable.entries), true to true),
)
for ((name, options, ok) in cases) {
val db = reachDb(name, options)
for ((q, allowed) in listOf(derivedKeyword to ok.first, memoryKeyword to ok.second)) {
if (allowed) {
assertEquals(10, rows(db.execute(q)), name)
db.query(q).use { }
db.prepare(q).use { }
} else {
assertEquals("API-025", code(assertThrows<MiniGrafException.Api> { db.execute(q) }), name)
assertEquals("API-025", code(assertThrows<MiniGrafException.Api> { db.query(q) }), name)
assertEquals("API-025", code(assertThrows<MiniGrafException.Api> { db.prepare(q) }), name)
}
}
db.close()
}
}

@Test
fun transactionChunkFactsCommitsALargeTransaction() {
val path = dir.resolve("chunk.graph").toString()
Minigraf.openWithOptions(path, Minigraf.options().transactionChunkFacts(2).build()).use { db ->
db.execute("(transact [" + (0 until 10).joinToString("") { "[:e$it :n $it]" } + "])")
}
Minigraf.open(path).use { db ->
assertEquals(10, rows(db.execute("(query [:find ?n :where [?e :n ?n]])")))
}
val e = assertThrows<MiniGrafException.Api> {
Minigraf.openWithOptions(
dir.resolve("bad.graph").toString(),
Minigraf.options().transactionChunkFacts(-1).build(),
)
}
assertEquals("API-017", code(e))
}

@Test
fun maxIterationsOption() {
assertEquals(10, rows(reachDb("default").execute(reach)))
val e = assertThrows<MiniGrafException> { reachDb("one", Minigraf.options().maxIterations(1)).execute(reach) }
assertEquals("INT-020", code(e))
assertEquals(10, rows(reachDb("max", Minigraf.options().maxIterations(Long.MAX_VALUE)).execute(reach)))
val bad = assertThrows<MiniGrafException.Api> { reachDb("bad", Minigraf.options().maxIterations(-1)) }
assertEquals("API-017", code(bad))
}

@Test
fun logWriterTakesTheNewOptions() {
val out = dir.resolve("out.graph")
val options = Minigraf.options().allowOverrides().transactionChunkFacts(2).maxIterations(5).build()
Minigraf.createLogWriter(out.toString(), options).use { it.finish() }
assertTrue(Files.exists(out))
}

@Test
fun settersDeriveNewQueries() {
// The setters are not gated: every override keyword is refused here.
val db = reachDb("setters", Minigraf.options().allowOverrides())
val cases = listOf<Triple<String, (MiniGrafPreparedQuery, Long) -> MiniGrafPreparedQuery, Pair<Long, String>>>(
Triple(reach, { q, n -> q.withMaxDerivedFacts(n) }, 1L to "INT-020"),
Triple(reach, { q, n -> q.withMaxIterations(n) }, 1L to "INT-020"),
Triple(grouped, { q, n -> q.withQueryMemoryLimit(n) }, 16L to "QRY-012"),
)
for ((query, setter, limit) in cases) {
val pq = db.prepare(query)
val before = rows(pq.execute())
val derived = setter(pq, limit.first)
assertEquals(limit.second, code(assertThrows<MiniGrafException> { derived.execute() }))
assertEquals(
limit.second,
code(assertThrows<MiniGrafException> { derived.query().use { it.batches().toList() } }),
)
assertEquals(before, rows(pq.execute()))
assertEquals(before, rows(setter(derived, Long.MAX_VALUE).execute()))
assertEquals("API-017", code(assertThrows<MiniGrafException.Api> { setter(pq, -1) }))
}
}

@Test
fun chainedSettersKeepEarlierLimits() {
val pq = reachDb("chain").prepare(reach)
val chained = pq.withMaxDerivedFacts(1).withMaxIterations(1).withMaxIterations(Long.MAX_VALUE)
assertEquals("INT-020", code(assertThrows<MiniGrafException> { chained.execute() }))
assertEquals(10, rows(chained.withMaxDerivedFacts(Long.MAX_VALUE).execute()))
}

@Test
fun derivedQueryKeepsItsDatabaseOpen() {
val db = reachDb("alive")
val pq = db.prepare(reach)
val derived = pq.query().use { cursor ->
val d = pq.withMaxIterations(10)
assertEquals(10, cursor.batches(3).sumOf { mapper.readValue<List<Any>>(it).size })
d
}
pq.close()
db.close()
assertEquals(10, rows(derived.execute()))
}
}
Loading
Loading
0