Skip to content
stassPublic

Repository files navigation

relic

relic is an ultra-fast embeddable Datalog engine for dependency analysis, graph queries and reasoning over tables. Describe your data as facts and the relationships you want as rules: relic follows dependency chains, computes reachability and derives answers across any number of steps.

Run queries directly from your shell or embed the same engine in your C application with librelic. No program compilation step, no server, and no third-party runtime dependencies. Import CSV or TSV, explore interactively, and send the answers back into your pipeline.

You can also use the optional WASM module to run relic directly in the browser.

It's designed to be friendly enough for everyday work and fast enough to be a part of code analysis pipelines or binary analysis frameworks.

The project website includes a quickstart, language tutorial, C API overview and a browser playground. The performance page shows recorded benchmarks and lists the methods used by the engine.

  • High performance. In our benchmark suite, relic beats leading Datalog engines on most workloads, often by a wide margin, including compiled Soufflé.
  • Query-aware execution. Query-directed evaluation and indexed joins avoid unnecessary work; recursive evaluation reuses earlier results. Multi-core execution shares large rounds across available processors.
  • Fits into the tools you use. A command-line tool for scripts, a REPL for exploration, and a C API for applications. Text, CSV, TSV and JSON output make results easy to consume.
  • Portable. C11, BSD 2-Clause licensing, and no required third-party runtime libraries. Optional libedit adds REPL line editing.

Find what a change affects

Which applications depend on a database, even through other services? These two rules follow the entire dependency chain. Save this as impact.dl:

depends(web, api).
depends(api, database).
depends(worker, api).

affected(App, Changed) :- depends(App, Changed).
affected(App, Changed) :- depends(App, Middle), affected(Middle, Changed).

This query returns applications that depend directly or indirectly on the database:

$ relic -s -q 'affected(App, database)?' impact.dl
api
web
worker

Lowercase identifiers such as api are symbols; uppercase identifiers such as App are variables. :- means "if", and a query ends in ?. -s sorts the answers. The same rules handle longer dependency chains and cycles.

Use relic -i impact.dl for interactive queries, or include queries in the program itself. EXAMPLES.md provides runnable examples of negation, arithmetic, aggregates, table processing and the C API.

Data files

Import data with -I and declare column types with -T. For example, edge.tsv can hold these two tab-separated rows:

a	b
b	c

Save the rules and query as reach.dl:

% What a can reach, over edges given as a table.
path(X, Y) :- edge(X, Y).
path(X, Z) :- edge(X, Y), path(Y, Z).
path(a, X)?

The file name edge.tsv supplies the predicate name and input format:

$ relic -T edge:symbol,symbol -I edge.tsv reach.dl
b
c

Programs contain facts, rules and queries; the command line chooses the files. Loading someone else's program gives it no file access of its own; bound its memory and tuples with -l memory= and -l tuples=.

-F chooses the answer format, and -o writes answers to a file. -O exports a whole relation after the queries have run: -O path.tsv writes a table for -T and -I, and -O path.dl writes typed Datalog facts that another run can load:

$ relic -n -T edge:symbol,symbol -I edge.tsv -O path.dl reach.dl && relic -q 'path(a, X)?' path.dl
b
c

See the table examples and relic(1) for headers, column selection and explicit predicate names.

Use cases

  • Dependency analysis. Follow package, build or service dependencies, detect cycles and compute the impact of a change. The dependency planner demonstrates scheduling with prerequisites.
  • Graph queries. Compute network reachability, trace relationships and find paths. The metro example combines recursion and aggregation to find the fewest stops between stations.
  • Static analysis. Express call-graph reachability or points-to analysis as rules over facts extracted from source code. The benchmark suite includes points-to inputs from Apache httpd, PostgreSQL and Linux.
  • Table processing. Join CSV and TSV exports, group files by directory, or compute counts, sums and rankings. A game leaderboard demonstrates aggregation over imported tables.
  • Relationship modeling. Derive indirect relationships from base facts. The family tree covers ancestry, cousins, negation and descendant counts.

How relic keeps queries fast

  • Recursive evaluation. Semi-naive evaluation avoids repeating work from earlier rounds. Indexed joins and automatic join ordering keep lookups focused. Magic Sets specialize evaluation to a query's bindings, so a focused question can avoid computing an entire relation.
  • Multi-core execution. -j 0 uses the available processors, up to 256 threads; -j 16 requests sixteen. Large evaluation rounds share their work, while small rounds stay on one thread. Answers, their order and diagnostics stay the same at every thread count.
  • Inspect the work. -e explains the query plan; -X stats reports the work the engine does, so you can understand how a query is evaluated.

Install

With Homebrew installed:

brew install stass/tap/relic

The relic formula installs the command-line tool, library, header and manual pages.

From a release tarball, a C11 compiler, make and a POSIX shell are enough. Installing into /usr/local usually needs root; choose another --prefix to install as yourself:

./configure --prefix=/usr/local
make
make check
make install

This installs the relic tool and its manual page, the shared and static librelic, the header <relic.h>, the relic(3) manual page and the librelic.pc pkg-config file under the prefix. Out-of-tree builds are supported and preferred:

mkdir build && cd build
../configure && make && make check

From a git checkout, generate the build system first. This needs autoconf 2.69, automake 1.13 and libtool 2.4.2 or newer, which are maintainer tools only:

./autogen.sh

The configure options that matter most:

  • --prefix=DIR chooses where to install; DESTDIR staging works as usual.
  • --with-libedit=auto|yes|no controls line editing in the interactive mode. The default, auto, uses libedit if it is present. It is the only optional dependency.
  • --disable-threads builds an engine that runs on the calling thread alone.
  • --disable-shared or --disable-static installs only one kind of library.
  • --enable-thinlto links with LLVM ThinLTO.
All build options
--enable-debug          assertions, -O0 -g3                    (default: no)
--enable-werror         treat warnings as errors               (default: no)
--enable-thinlto        LLVM link-time optimization            (default: no)
--disable-threads       evaluate on the calling thread alone   (default: threads)
--enable-asan           AddressSanitizer                       (default: no)
--enable-ubsan          UndefinedBehaviorSanitizer             (default: no)
--enable-lsan           LeakSanitizer, where it stands alone   (default: no)
--enable-msan           MemorySanitizer, clang on Linux        (default: no)
--enable-tsan           ThreadSanitizer                        (default: no)
--enable-coverage       gcov or llvm-cov instrumentation       (default: no)
--enable-fuzzers        build tests/fuzz, clang only           (default: no)
--with-libedit=auto|yes|no
                        line editing and history in the REPL   (default: auto)

ThinLTO optimizes across source files at link time. Enable it with ./configure --enable-thinlto; use CFLAGS='-O3 -g' to select the optimization level used by the benchmark builds. Configuration checks the selected compiler, archiver, archive indexer, symbol reader and linker, and fails if they cannot build ThinLTO. Clang with the native toolchains on macOS and FreeBSD supports this option. Other installations may need matching LLVM tools selected through CC, AR, RANLIB and NM, and an LTO-capable linker selected through LDFLAGS.

Executables and shared libraries contain native code. The installed static archive contains LLVM bitcode, so programs linking it need a compatible compiler and linker. For a static-only installation, use pkg-config --static --libs librelic to include its private dependencies. ThinLTO adds no runtime dependency and does not change the runtime worker count. It can increase executable size; function alignment is a separate compiler setting.

LLVM bitcode also retains the compiler's source filename, which -ffile-prefix-map does not rewrite. For distributable static archives, build in the source tree or invoke configure through a relative source path so that this filename does not contain an absolute build-machine path.

Sanitizer suites and strict checks
make check          the unit and language suites
make check-asan     reconfigure with AddressSanitizer, rebuild, run the suite
make check-lsan     the same under LeakSanitizer, where it stands alone
make check-msan     the same under MemorySanitizer, where it is supported
make check-ubsan    the same under UndefinedBehaviorSanitizer
make check-tsan     the same under ThreadSanitizer, with threads enabled

Each sanitizer suite configures a disposable build tree under disposable/ in the current build directory, from a copy of the distributed sources, so it never leaves instrumented objects in the tree you work in and works whether that tree was configured in place or not. A sanitizer the platform does not support reports that and succeeds rather than failing the build.

A few tests need a tool the build does not, such as mandoc, nm or pkg-config, and are skipped without it. On a machine set up to run every check, set RELIC_STRICT_CHECK=yes in the environment: a skipped test then fails, and so do a sanitizer suite the compiler cannot build and an installcheck without pkg-config. A skip that is expected there is named in RELIC_ALLOWED_SKIPS, a space-separated list of test file names and targets:

RELIC_STRICT_CHECK=yes RELIC_ALLOWED_SKIPS=symbols.sh make distcheck

Supported platforms

relic supports macOS, Linux with glibc or musl, and FreeBSD. OpenBSD and NetBSD are portability targets without release validation. Continuous integration builds and tests a release tarball on Linux with glibc and musl and on FreeBSD for every change.

Use from C

librelic installs one header, <relic.h>, and a pkg-config module named librelic. Compile and link a program against it with:

cc -o sample sample.c $(pkg-config --cflags --libs librelic)

If the library was installed under a prefix that pkg-config does not search, such as --prefix=$HOME/.local, name its directory first: PKG_CONFIG_PATH=$HOME/.local/lib/pkgconfig. For a static-only installation, add --static to the pkg-config command. A program linked against the shared library also has to find it when it runs: install into a directory the system searches (on Linux, run ldconfig after installing), set LD_LIBRARY_PATH to the library directory, or link with -Wl,-rpath,DIR.

This sample.c loads the program of the example above, answers the query and prints each application it finds:

#include <stdio.h>
#include <stdlib.h>

#include <relic.h>

/* Called once per answer row; a nonzero return stops the query. */
static int
print_row(void *arg, const relic_value_t *values, size_t count)
{
	relic_t *ctx = arg;

	/* A symbol is safe to print as it is; escape a string before it
	 * reaches a terminal. */
	if (count > 0 && values[0].type == RELIC_SYMBOL)
		puts(relic_string(ctx, values[0].v.id, NULL));
	return (0);
}

int
main(void)
{
	static char name[] = "sample";
	relic_config_t cfg = { 0 };
	relic_query_t *query = NULL;
	relic_t *ctx;
	int status;

	/* A zeroed configuration asks for every default. */
	cfg.max_memory = (size_t)256 << 20;
	cfg.threads = 4;
	ctx = relic_create_config(&cfg, sizeof cfg);
	if (ctx == NULL)
		return (EXIT_FAILURE);
	relic_diag_set(ctx, relic_diag_stderr, name);

	status = relic_load_string(ctx, "impact",
	    "depends(web, api). depends(api, database).\n"
	    "depends(worker, api).\n"
	    "affected(A, C) :- depends(A, C).\n"
	    "affected(A, C) :- depends(A, M), affected(M, C).\n");
	if (status == 0)
		query = relic_query_prepare(ctx, NULL, "affected(App, database)?");
	if (query == NULL || relic_query_run(ctx, query, print_row, ctx) != 0)
		status = -1;

	relic_query_destroy(query);
	relic_destroy(ctx);

	if (fflush(stdout) == EOF || ferror(stdout))
		status = -1;
	return (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}

It prints api, web and worker. The order of the rows is unspecified, though the same on every run; relic_value_compare() orders them when you need a particular order. A few conventions apply to the whole API:

  • Every failure is reported by the return value: -1 from a function that returns int, NULL from one that returns a pointer. For a call on a context, the diagnostic callback receives the explanation, and relic_error() and relic_error_class() describe the most recent failure; relic_create() reports through errno. Nothing exits the process.
  • A structure the library reads or fills, a relic_config_t for example, is passed with its size, as in relic_create_config(&cfg, sizeof cfg). This lets a later release add fields without breaking a program built against this one. Zero the structure before setting its fields.
  • Contexts share nothing, so each thread may use its own. One context is used by one thread at a time; relic_interrupt() is the one call another thread, or a signal handler, may make on it.
  • A query's rows go to a callback as they are derived, or are collected into a result that outlives the context.
  • Only symbols that begin with relic_ are exported. The RELIC_UNSTABLE_* configuration switches exist for testing and are not part of the interface.

relic(3) describes every function. examples/query.c and examples/embed.c are complete programs that use only the public API; make installcheck builds embed.c against the installed library.

Performance

On AMD Ryzen Threadripper PRO 5995WX with 256 GiB RAM, relic records the lowest median wall time on 30 of 31 comparable workloads with 64 threads, and 24 of 31 with one thread, against completed rival runs. The suite compares compiled Souffle (with and without Magic Sets), interpreted Souffle, Nemo, SWI-Prolog, clingo, DuckDB and SQLite.

The charts show every scale-1 workload at the parallel thread count, grouped by kind. Each bar is an engine's speed relative to relic, which is fixed at 1×: a shorter bar means relic is faster, and a bar taller than relic's means the rival is faster. Missing results are labeled rather than plotted as zero.

Relative speed on transitive-closure benchmarks, comparing relic with Soufflé Magic, compiled Soufflé, interpreted Soufflé and DuckDB.

Relative speed on queries with a bound argument.

Relative speed on graph reachability and distance benchmarks.

Relative speed on same-generation benchmarks.

Relative speed on points-to and program-analysis benchmarks.

Relative speed on table-processing and startup benchmarks.

Charts are generated from the recorded timings with plot-performance.py.

All 31 workloads below show relic, compiled Soufflé with Magic Sets, and standard compiled Soufflé. The fastest rival column names the fastest completed rival at this scale and thread count. Speedup compares relic with that rival. relic runs Datalog directly, without a program compilation step.

Workload relic Souffle Magic Souffle compiled Fastest rival relic speedup
chain-right 2.99 ms 1.6 s 1.55 s DuckDB: 1.42 s 476.3x
chain-left 2.69 ms 28 ms 1.63 s Souffle Magic: 28 ms 10.4x
sg-acyclic-bf 2.4 ms 15.6 ms 64.1 ms Souffle Magic: 15.6 ms 6.5x
tc-cyclic-bf 18.1 ms 107 ms 103 ms Souffle compiled: 103 ms 5.7x
chain-closure 331 ms 2.16 s 2.02 s DuckDB: 1.84 s 5.5x
grid-reach 18.3 ms 106 ms 100 ms Souffle compiled: 100 ms 5.5x
tree-sg-bound 4.97 ms 18.2 ms 417 ms Souffle Magic: 18.2 ms 3.7x
tc-sparse-cyclic 143 ms 504 ms 468 ms Souffle compiled: 468 ms 3.3x
tc-acyclic-bf 12.8 ms 40.6 ms 63 ms Souffle Magic: 40.6 ms 3.2x
tc-cyclic 157 ms 583 ms 495 ms Souffle compiled: 495 ms 3.1x
tc-cyclic-fb 12.8 ms 37.5 ms 274 ms Souffle Magic: 37.5 ms 2.9x
dist-bounded 290 ms 997 ms 942 ms DuckDB: 841 ms 2.9x
tc-acyclic-fb 12.1 ms 33 ms 118 ms Souffle Magic: 33 ms 2.7x
startup 720 us 2.01 ms 1.9 ms Souffle compiled: 1.9 ms 2.6x
sg-cyclic 190 ms 583 ms 476 ms Souffle compiled: 476 ms 2.5x
tc-sparse-acyclic 35.1 ms 90.8 ms 87.6 ms Souffle compiled: 87.6 ms 2.5x
tc-acyclic 119 ms 283 ms 247 ms Souffle compiled: 247 ms 2.1x
tree-sg-all 37.6 ms 77.2 ms 74.2 ms Souffle compiled: 74.2 ms 2.0x
sg-acyclic 133 ms 291 ms 244 ms Souffle compiled: 244 ms 1.8x
graph-left 47.6 ms 70.8 ms 29.4 s Souffle Magic: 70.8 ms 1.5x
degree-count 57.8 ms 85.8 ms 86.6 ms Souffle Magic: 85.8 ms 1.5x
graph-reach 44.8 ms 67.3 ms 66.3 ms Souffle compiled: 66.3 ms 1.5x
cspa-postgresql 20.5 s timeout 29.3 s Souffle compiled: 29.3 s 1.4x
cspa-httpd 17.7 s timeout 23.9 s Souffle compiled: 23.9 s 1.3x
tc-nonlinear 60.6 ms 107 ms 81.1 ms Souffle compiled: 81.1 ms 1.3x
files-grouped 73.9 ms 199 ms 167 ms DuckDB: 87.6 ms 1.2x
cspa-linux 7.67 s timeout 8.97 s Souffle compiled: 8.97 s 1.2x
cspa 101 ms 11.9 s 117 ms Souffle compiled: 117 ms 1.2x
tasks-ready 66.6 ms 76.9 ms 74.2 ms Souffle compiled: 74.2 ms 1.1x
facts-join 106 ms 220 ms 218 ms DuckDB: 116 ms 1.1x
andersen 94.6 ms timeout 93.3 ms Souffle compiled: 93.3 ms 1.0x

These are scale-1 medians with 64 threads on AMD Ryzen Threadripper PRO 5995WX with 256 GiB RAM. Times include startup, loading, evaluation and complete answer serialization to discarded stdout for every engine; compilation is excluded. Rival timings outside chain-closure and tree-sg-all come from an earlier run on the same host and engine builds; the full results give both runs.

See the full results for all workloads, timing spread and memory use, and methodology to reproduce the comparison.

Reliability and testing

relic checks its optimizations against a simple reference evaluator, compares serial and parallel execution, and tests failure paths as well as successful queries.

  • Differential fuzzing. Four libFuzzer targets exercise program loading, evaluation, table import and regular expressions. The evaluation target compares optimized answers against naive evaluation of the whole program, catching wrong results as well as crashes.
  • Randomized testing. The randomized suite compares evaluation strategies with indexing, join reordering, Magic Sets and parallel execution enabled or disabled. Weekly CI is configured for 10,000 program seeds and fifteen minutes per fuzz target under AddressSanitizer and UndefinedBehaviorSanitizer.
  • Regression and sanitizer suites. The fuzz corpora are replayed by make check. Dedicated suites run under address, undefined-behavior, thread, memory and leak sanitizers where supported.
  • Resource limits and file access. Tuple and evaluation-memory limits stop runaway derivations with diagnostics, and an input limit bounds the size of one program file or one field of an imported table. Programs express computation; the runner chooses which data files they can read and write. The memory limit covers evaluation storage, not total process memory.

The testing design explains the reference checks, randomized testing and fuzzing. Run them locally with:

make check
make check-random RELIC_SEEDS=10000

# In a separate build configured with clang and
# --enable-fuzzers --enable-asan --enable-ubsan:
make fuzz FUZZ_SECONDS=900

Limitations

A query that binds an argument is answered through a Magic Sets rewrite, which derives only what the query can reach. A recursive rule that calls its own predicate twice, with the bound argument passed to the first call, costs that rewrite a second relation as large as the closure it derives. Of these two definitions of a path, called as path(a, X)?:

path(X, Z) :- path(X, Y), path(Y, Z).
path(X, Z) :- path(X, Y), edge(Y, Z).

the first keeps a second relation holding a copy of every path the rewrite derives, and the second does not. Both give the same answers, and the copy counts against the memory limit like any other relation. relic -e shows the copy as a predicate named sup$.... Where memory matters, prefer the linear form.

Documentation

File Contents
EXAMPLES.md a tour of relic through programs you can run
man/relic.1 the tool and the language
man/relic.3 the library
specs/README.md the design documents, where to start reading
specs/architecture.md the target design of the system
specs/language.md the specification of the language
specs/style.md code style, binding on all relic-owned code
docs/research.md papers, reference implementations and local methods behind the design
NEWS what changed in each release
TODO.md open work, by severity

License

BSD 2-Clause. See LICENSE.

Releases

Packages

Contributors

Languages