8000 Clarify Swift API documentation and test commentary by adityamukho · Pull Request #31 · project-minigraf/minigraf-swift · 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
115 changes: 65 additions & 50 deletions README.md
8000
Original file line number Diff line number Diff line change
Expand Up @@ -90,20 +90,22 @@ try out.finish() // out.close() instead abandons the build and leaves no file
`validTimeForever` is the `validTo` of a fact valid forever. `MiniGrafError.message`
starts with the error's code, such as `[API-015]`.

`OpenOptions(queryMemoryLimit: bytes)` caps the bytes one query may hold, counted per
entry by the operators that keep state (join build sides, negation and `or` tables,
distinct sets, aggregate groups, window rows, rule-derived facts). A query that would hold
more throws `MiniGrafError.Query` with QRY-012 and frees what it held. The default, and
`Int64.max`, is no limit. Rows a cursor returns are not counted, so read a large answer
with `query(datalog:)`.
`OpenOptions(queryMemoryLimit: bytes)` limits the bytes a query counts for
retained state. The query counts entries on the build side of joins, in negation and `or`
tables, distinct sets, aggregate groups, window rows and rule-derived facts.
If it would exceed the limit, it releases its state and throws
`MiniGrafError.Query` with QRY-012. By default there is no limit; `Int64.max`
also means no limit. Rows returned by a cursor are not counted. Use
`query(datalog:)` to read a large result in batches.

Query text may override some settings with keywords such as `:max-derived-facts 1000`.
`OpenOptions(allowOverrides:)` lists the `Overridable` keywords it may use
(`.maxDerivedFacts`, `.maxResults`, `.queryMemoryLimit`, `.maxIterations`). Left `nil`, the
defaults apply: `Overridable.defaults`, read from the core library (today
`.maxDerivedFacts`, `.maxResults` and `.maxIterations`). A list replaces the defaults, it
does not add to them, and `[]` refuses every keyword: a query that uses one throws
`MiniGrafError.Api` with `[API-025]` from `execute`, `query` and `prepare`.
(`.maxDerivedFacts`, `.maxResults`, `.queryMemoryLimit`, `.maxIterations`). Use
`nil` for `Overridable.defaults` from the core library: currently
`.maxDerivedFacts`, `.maxResults` and `.maxIterations`. A nonempty list replaces
the defaults, and `[]` disables all query-text overrides. An override not on
the allowed list throws `MiniGrafError.Api` with `[API-025]` from `execute`,
`query` and `prepare`.

```swift
let db = try MiniGrafDb.openWithOptions(path: path, options: OpenOptions(
Expand Down Expand Up @@ -145,12 +147,12 @@ A set inside a set throws `MiniGrafError.Api` with `[API-021]`. Set values come
JSON arrays from `execute` and as `MiniGrafValue.set` in fact records.

`MiniGrafError` is `.Parse`, `.Query`, `.Storage`, `.Api` (a bad argument, a closed
object, a bind mistake) or `.Other`.
object, or an invalid query binding) 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. `Int64.max` means no limit and a
unchanged. `allowOverrides` does not restrict these setters. A permitted
override in the query text still takes precedence. `Int64.max` means no limit and a
negative value throws `[API-017]`. A derived query keeps its database open, as any
prepared query does.

Expand Down Expand Up @@ -214,8 +216,9 @@ _ = try db.execute(datalog: "(query [:find ?a (product ?a :over (:order-by ?a))
callbacks short: a query on the main thread blocks it for as long as they run.
- **Cost.** Each call crosses the FFI once: one foreign call per value.
- **Re-entry.** A callback may query the same database, open a cursor or register another
function. Inside a write transaction, the calls the core refuses there still return
`INT-001`.
function. Inside a write transaction, the calls listed under
[Write transactions](#write-transactions) return `INT-001`. Opening a cursor
is a call to `query`.

## Write transactions

Expand All @@ -236,26 +239,37 @@ try db.withWriteTransaction(options: TxOptions(chunkFacts: 10_000)) { tx in
}
```

- `db.beginWrite()` or `db.beginWrite(options: TxOptions(...))` returns a
`MiniGrafWriteTransaction` to end yourself; `withWriteTransaction` runs a closure and
returns its result. An option left `nil` is the database's: `synchronous`
(`.full` / `.normal`) is this commit's WAL sync, `chunkFacts` the facts staged before
a file database writes the transaction in chunks (negative is API-017). Read-only
databases throw API-014.
- `db.beginWrite()` and `db.beginWrite(options: TxOptions(...))` return a
`MiniGrafWriteTransaction`. Call `commit()` or `rollback()` yourself.
`withWriteTransaction` runs a closure and returns its result. A `nil` option
uses the database default. `synchronous` (`.full` or `.normal`) controls WAL
sync for this commit. `chunkFacts` sets how many facts the transaction stages
before a file-backed database writes in chunks; a negative value throws
API-017. Read-only databases throw API-014.
- `tx.execute(datalog:)` returns what `db.execute` returns; a staged write returns
`{"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`, `incomingRefs` and `commit` then
throw API-018, and `rollback` does nothing.
- Commit is always explicit. A transaction released while open rolls back; ARC releases
it when the last reference goes, but end it yourself rather than rely on that.
- A 8000 n open transaction holds the database's write lock until it finishes, so end every
transaction explicitly or through `withWriteTransaction`. 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`, `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.
- `tx.commit()` applies the writes as one transaction; `tx.rollback()` discards
staged writes. Once `commit()` takes the transaction, it finishes it even
if it throws. An error before the facts are applied leaves them unapplied,
but automatic checkpointing can fail after application, and deleting the
WAL can fail after a large transaction has committed. Check whether the
facts were applied before retrying. If the failed checkpoint leaves the
handle rejecting writes with STG-046, reopen it and check again. On a
finished transaction, `execute`, `incomingRefs` and `commit` throw API-018,
and `rollback` does nothing.
- Commit is always explicit. When ARC releases the last reference to an open
transaction, it rolls back. Finish it yourself or use `withWriteTransaction`
so the write lock is released promptly.
- On the thread that opened the transaction, database calls to `execute`,
`query`, `prepare`, `factLog`, `checkpoint`, another `beginWrite` and prepared
queries fail with INT-001. That also applies to those calls from user
functions run by the transaction. A user function gets INT-001 if it calls
`execute`, `incomingRefs`, `commit` or `rollback` on its own transaction.
- On other threads, writes and attempts to start a transaction wait until it
finishes; queries still see committed data. Use the transaction on the thread
that opened it. A different thread that uses the transaction and then writes
through the database can wait for that same transaction to finish.
- Rules registered inside a transaction stay registered after a rollback.
- The transaction keeps its database open until it is released.

Expand All @@ -282,32 +296,33 @@ try db.withWriteTransaction { tx in
}
```

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.
The lookup sees earlier writes in this transaction without changing them.
A complete result contains `IncomingRef` records with canonical lowercase UUID
`source` strings and `attribute` strings, in no specified order. A complete
result can contain no links; an exhausted result never contains a partial list.
Require a complete result before staging deletes. If the result is exhausted,
retry with higher limits or stop. Earlier writes remain staged and 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`
- Both limits are required and neither has an unlimited value. A lookup can
succeed exactly at either limit. 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
`0, 0` completes empty only when no record needs inspection. Large limits do
not allocate proportional memory up front.
- The links budget caps distinct `(source, attribute)` pairs. The records budget
- The link limit caps distinct `(source, attribute)` pairs. The record limit
caps fact versions examined across all layers, including superseded versions,
retractions and lookahead. The returned record count never exceeds that budget;
retractions and lookahead. The returned record count never exceeds that limit;
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.
- Invalid UUIDs and negative or unrepresentable limits give `API-017`. A finished
transaction gives `API-018` before argument validation. A callback that
calls back into its own transaction gets `INT-001` before locking or
validating arguments. Storage and decoding errors remain errors. A complete
result, an exhausted result or `API-017` leaves the transaction open for
further statements, retry, commit or rollback.

## Building from source

Expand Down
2 changes: 1 addition & 1 deletion Tests/swift/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ do {
try writer.finish()
check(FileManager.default.fileExists(atPath: out), "log writer takes the new options")

// The setters are not gated: every override keyword is refused here.
// These setters still work when query-text overrides are disabled.
let db = try reachDb("setters", OpenOptions(allowOverrides: []))
let setters: [(String, (MiniGrafPreparedQuery, Int64) throws -> MiniGrafPreparedQuery, Int64, String)] = [
(reach, { try $0.withMaxDerivedFacts(n: $1) }, 1, "[INT-020]"),
Expand Down
Loading
0