Skip to content
coreseekdevPublic
forked from leostera/datafox

About

async streaming datalog engine with pluggable backends

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

datafox

Ask questions of your data in Datalog, from Rust, and get the answers fast.

datafox is a Datalog engine you embed in your program. You give it facts, such as the edges of a graph, the symbols of a codebase or the variables of a program, and rules that say what follows from them. Then you ask questions: what reaches what, what points to what, what's never used. datafox finds every answer, fast.

  • Fast. At the largest size of each of our benchmarks, datafox on one thread is 1.6× to 12.9× faster than the fastest of Soufflé, Ascent, Crepe, datafrog and Nemo on any number of threads. On 16 or 20 threads, it's 4.5× to 20.0× faster (numbers), and enabling the optional gpu feature accelerates 6 of 8 benchmarks an additional 1.3× to 5.0× over 20-core CPU on Metal, Vulkan or DX12 via wgpu. It reads your program when it runs, so there's no code to generate and no build step.
  • Correct. Before timing anything, every benchmark run checks datafox's answers against Soufflé's. An oracle compares the two on tens of thousands of random programs, and the adaptive dense representation proofs are mechanized in Lean 4 (formal/).
  • Works on your data. Load facts from tab-separated text on every core, 16 million edges (278 MB) in 68 ms, or answer from your own store by implementing a trait.
  • Expressive. Recursion, stratified negation, aggregates (count, sum, min, max), arithmetic, comparisons, and string and regex tests.
  • Made to embed. You can cache and serialize prepared queries, and add facts, relations and operators of your own. Errors are typed, a parse error points at the text it's about, and the crate has no unsafe code.

Quick start

[dependencies]
datafox = "0.5"

To enable optional GPU compute acceleration (zero extra dependencies when disabled, still zero unsafe):

[dependencies]
datafox = { version = "0.5", features = ["gpu"] }

datafox needs Rust 1.88 or later.

use datafox::{
    DatafoxClient, DatafoxConfig, InMemoryStorage, Layered, Value, evaluate, parse_program,
};

fn main() -> datafox::Result<()> {
    // Facts: a small graph, kept in memory.
    let edges = [(1, 2), (2, 3), (3, 4)];
    let storage = InMemoryStorage::from_facts([(
        "edge".to_string(),
        edges
            .iter()
            .map(|&(from, to)| vec![Value::integer(from), Value::integer(to)])
            .collect(),
    )]);

    // Rules say what follows from the facts. The query after them asks the question.
    let program = parse_program(
        "path(X, Y) :- edge(X, Y).
         path(X, Z) :- path(X, Y), edge(Y, Z).
         path(1, To)",
    )?;

    // Evaluate the rules, then answer the query over the facts and what the rules derived.
    let derived = evaluate(&program, &storage, None)?;
    let layered = Layered::new(&storage, &derived);
    let datafox = DatafoxClient::new(DatafoxConfig::new(&layered))?;
    let mut reachable: Vec<Value> = datafox
        .eval(&program.queries[0])?
        .filter_map(|answer| answer.lookup("To").cloned())
        .collect();
    reachable.sort();

    assert_eq!(reachable, [2, 3, 4].map(Value::integer));
    Ok(())
}

Writing programs

A program has facts and rules, followed by the queries to answer:

% Facts: what's true. A program may state some of its own, next to the store's.
layer("http", 3).
layer("store", 1).

% Rules: what follows. A rule may be recursive.
path(X, Y) :- edge(X, Y).
path(X, Z) :- path(X, Y), edge(Y, Z).

% Negation, of a relation that doesn't depend on the rule's own.
unreachable(X) :- node(X), !path(1, X).

% An aggregate in the head, grouped by the head's other terms.
out(X, count(Y)) :- edge(X, Y).

% Queries come last, separated by `;`.
path(1, Y); out(X, N), N > 10; layer(Name, Level), startsWith(Name, "ht")
Form Example
Atom edge(From, To)
Variable Name
String constant "dbg!"
Integer constant 42
Wildcard _
Conjunction node(Node), text(Node, Text)
Negation node(Node), !test(Node)
Query set node(Node); edge(From, To)
Quoted predicate 'local://schema/name'(Entity, Value)
Binary expression (Line + 1) = 42
Aggregate, in a rule's head out(X, count(Y)), also sum, min and max
Comment % to the end of the line
Builtin Example
Equality and order A = B, A != B, Start < End, Start <= End, End > Start, End >= Start
The same, by name eq(A, B), lt(A, B), lte(A, B), gt(A, B), gte(A, B)
Order in time before(Start, End), after(End, Start)
Text startsWith(Name, "lint"), endsWith(Name, ".rs"), contains(Text, "dbg!")
Text, negated notStartsWith(Name, "test"), notEndsWith(Name, ".rs"), notContains(Text, "dbg!"), !startsWith(Name, "test")
Regular expressions matchesRegex(Text, "^dbg!"), notMatchesRegex(Text, "^dbg!")
Arithmetic (X + 1) = Y, (X - 1) = 0, (X * 2) > 10, (X / 2) = 4

The rules a program must follow:

  • Every variable in a rule's head, and every variable in a negated atom or a builtin, must first be bound by a positive atom.
  • A rule may negate, or aggregate over, only relations that don't depend on its own. Otherwise evaluation fails with NotStratifiable, which names both relations.
  • A relation has one arity everywhere it's used.

Using datafox from Rust

To Use
Answer a query over your facts parse_query, then DatafoxClient::eval
Evaluate rules, then query what they derive parse_program, evaluate, then Layered
Evaluate only what some relations need evaluate(&program, &store, Some(&["out"]))
Load facts from tab-separated text, on every core InMemoryStorage::load_facts
Build dense-numbered facts directly from Rust NumberedFactsBuilder, FactId, and InMemoryStorage::from_numbered
Answer from your own store implement FactStore, or Storage to stream facts asynchronously
Prepare a query once and run it many times DatafoxClient::prepare, then eval_prepared. A PreparedQuery can be serialized.
Compile a program once for many stores one DatafoxEnvironment with a PlanningCache, then evaluate_in
Accelerate dense recursive strata on GPU (gpu feature) DatafoxEnvironment::builder().try_with_gpu(), or GpuAccelerator::new + .with_gpu(...)
Add facts, relations and operators of your own Prelude
Answer a query on several threads DatafoxConfig::parallel() and .threads(n)
Get each answer as it's found DatafoxClient::stream
Write queries back out, formatted format_query, format_queries

Layered is itself a store, so programs can build on each other: a library's relations under the relations of your rules.

evaluate and load_facts use rayon's thread pool, which has every core by default. To use fewer, set RAYON_NUM_THREADS or call them inside a pool's install.

InMemoryStorage keeps its facts as numbers, which makes it the fastest store to evaluate over. A store of your own goes through the same API.

Load facts from text

use datafox::{FactColumn, InMemoryStorage, evaluate, parse_program};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // One fact a line, with tabs between columns, as in Soufflé's `.facts` files.
    let edges = "1\t2\n2\t3\n3\t4\n"; // or std::fs::read("edge.facts")?
    let mut storage = InMemoryStorage::new();
    storage.load_facts(
        "edge",
        &[FactColumn::Integer, FactColumn::Integer],
        edges.as_bytes(),
    )?;

    let program = parse_program(
        "path(X, Y) :- edge(X, Y).
         path(X, Z) :- path(X, Y), edge(Y, Z).",
    )?;
    let derived = evaluate(&program, &storage, None)?;
    assert_eq!(derived.len("path"), 6);
    Ok(())
}

If a line is malformed, load_facts returns a LoadError with the line number and loads none of the text.

Compile once, evaluate over many stores

A DatafoxEnvironment with a planning cache compiles each program and query once, however many stores you evaluate them over. Keep one for as long as your programs live.

use datafox::{
    DatafoxEnvironment, InMemoryStorage, PlanningCache, Value, evaluate_in, parse_program,
};

fn main() -> datafox::Result<()> {
    let program = parse_program(
        "path(X, Y) :- edge(X, Y).
         path(X, Z) :- path(X, Y), edge(Y, Z).",
    )?;
    let environment = DatafoxEnvironment::builder()
        .with_planning_cache(PlanningCache::unbounded())
        .build();

    // Chains of 1, 2 and 3 edges: the program is compiled for the first, and reused.
    for length in 1..=3 {
        let edges = (0..length)
            .map(|node| vec![Value::integer(node), Value::integer(node + 1)])
            .collect();
        let storage = InMemoryStorage::from_facts([("edge".to_string(), edges)]);
        let derived = evaluate_in(&environment, &program, &storage, None)?;
        assert_eq!(derived.len("path"), (length * (length + 1) / 2) as usize);
    }
    Ok(())
}

Add your own facts and operators

A prelude holds what every query may use, whatever the store: facts, relations such as startsWith, and operators such as +.

use datafox::{
    BinaryOperator, DatafoxClient, DatafoxConfig, InMemoryStorage, Prelude, Value,
    parse_query,
};

fn main() -> datafox::Result<()> {
    let prelude = Prelude::new()
        .with_fact("limit", [Value::integer(20)])
        .with_operator(BinaryOperator::from_option("plusTen", |left, right| {
            match (left, right) {
                (Value::Integer(left), Value::Integer(right)) => {
                    Some(Value::integer(left + right + 10))
                }
                _ => None,
            }
        }));
    let storage = InMemoryStorage::from_facts([(
        "size".to_string(),
        vec![
            vec![Value::string("small"), Value::integer(3)],
            vec![Value::string("large"), Value::integer(30)],
        ],
    )]);

    let datafox = DatafoxClient::new(DatafoxConfig::new(&storage).with_prelude(prelude))?;
    let query = parse_query("size(Name, Size), limit(Limit), (Size plusTen 0) > Limit")?;
    let names: Vec<Value> = datafox
        .eval(&query)?
        .filter_map(|answer| answer.lookup("Name").cloned())
        .collect();

    assert_eq!(names, [Value::string("large")]);
    Ok(())
}

Using datafox from JavaScript

@leostera/datafox, from 0.6.0, is the same engine as a native addon for Node.js and Bun, prebuilt for macOS, Linux and Windows:

import { Datafox, parse } from '@leostera/datafox';

const program = parse(`
  path(X, Y) :- edge(X, Y).
  path(X, Z) :- path(X, Y), edge(Y, Z).
  path(1, To)
`);
const derived = await new Datafox().evaluate(program, { edge: [[1, 2], [2, 3], [3, 4]] });
derived.answers(0); // [{ To: 2 }, { To: 3 }, { To: 4 }]

Performance

Time to answer at the largest size of each benchmark, in ms: from starting the process to having the answer, which is reading the facts, evaluating the program, and printing how many answers there are. Each time is the median of 3 runs on a Mac Studio (M1 Ultra, 20 cores) that was also running other work. Every engine ran on one thread, and the ones that can use more ran on 16 and 20 too: Soufflé, built with OpenMP (compiled Soufflé on 20 only), and Ascent, as ascent_par!. The table shows each other engine at its fastest, and datafox at the faster of 16 and 20 in the last column.

Benchmark, largest size Fastest other engine datafox, 1 thread datafox, 16 or 20 threads
Transitive closure of a 2,000-node chain 172.5, Ascent on 1 thread 27.1, 6.4× faster 26.2, 6.6× faster
Transitive closure of a random graph, 2,000 nodes 231.2, Ascent on 1 thread 17.9, 12.9× faster 18.5, 12.5× faster
Reachability in a random graph, 4M nodes and 16M edges 1,702.4, datafrog on 1 thread 1,046.2, 1.6× faster 195.5, 8.7× faster
Same generation in a binary tree of depth 11 306.6, compiled Soufflé on 20 threads 112.4, 2.7× faster 68.0, 4.5× faster
Andersen's points-to analysis, 40,000 variables 1,322.7, compiled Soufflé on 20 threads 167.2, 7.9× faster 87.5, 15.1× faster
Unreachable nodes, 4M nodes and 8M edges 990.0, datafrog on 1 thread 597.6, 1.7× faster 144.1, 6.9× faster
Out-degrees, a count and a max, 4M nodes 3,134.4, parallel Ascent on 20 threads 523.5, 6.0× faster 156.4, 20.0× faster
Unused and cross-file symbols in code, 2M symbols 3,794.6, Ascent on 1 thread 2,316.4, 1.6× faster 355.1, 10.7× faster

With --features gpu and a warm DatafoxEnvironment on the same Mac Studio (Apple M1 Ultra 64-core GPU, wgpu on Metal, median of 5 runs, exact parity with CPU and Soufflé), 6 of 8 workloads accelerate on GPU by 1.3× to 5.0× over 20-core CPU: out-degrees drops from 46.6 ms to 9.4 ms (5.0×), same-generation from 54.7 ms to 14.7 ms (3.7×, 20.8× faster than compiled Soufflé), reachability from 44.2 ms to 19.6 ms (2.3×), unreachable from 69.4 ms to 30.7 ms (2.3×), Andersen's from 80.0 ms to 40.8 ms (2.0×, 32.4× faster than compiled Soufflé), and random-graph TC from 11.9 ms to 8.9 ms (1.3×); sequential chains and string/join strata fall back to CPU automatically.

Ascent, Crepe and datafrog compile each program into their binary, and compiled Soufflé into C++, while datafox and Soufflé's interpreter read it when they run. On 16 and 20 threads, Soufflé couldn't run some of the benchmarks: it crashed. Nemo couldn't run Andersen's analysis within 5 minutes.

At the smallest sizes, starting threads can cost more than it saves: the smallest random graph takes datafox 8.6 ms on one thread and 15.7 ms on 16. The smallest code benchmark takes datafox 39.4 ms on one thread, 1.1× slower than Ascent's 36.2. bench/README.md describes the benchmarks and how they're measured, and bench/results has every engine's numbers at every size.

Correct answers

Before a benchmark times an engine, it compares that engine's answers with Soufflé's, as sets of rows. A point whose answers differ isn't a result. oracle generates random programs and facts, with joins, recursion, negation, comparisons and arithmetic, and checks that datafox gives Soufflé's answers on each one. When they disagree, it shrinks the program to a small failing case. Both are described in bench/README.md. The parser and evaluator are also fuzzed (fuzz/README.md).

Learn more

  • Papers: Systems paper (PDF) and Adaptive Dense Datalog theory (PDF) (sources in paper/).
  • Lean 4 proofs: formal/ — zero-sorry Lean 4 mechanization of origin soundness, codec coverage, pass-through word-OR lifting, changed_columns pruning, word-summary masks, and lazy promotion.
  • API reference: cargo doc -p datafox --open, or docs.rs for the released version.
  • ARCHITECTURE.md: how datafox works inside, and where each part lives.
  • CONTRIBUTING.md: how to build, test, benchmark and send changes.
  • docs/rfds: the designs behind it, with the measurements that shaped them.

License

MIT. See LICENSE.

About

async streaming datalog engine with pluggable backends

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages