API
Reference contexts
Source files for executed C and TypeScript card examples.backends-budget-mode.c
/* Select the callback location used by this displayed example. */
#define SELECTED_BACKEND_EXAMPLE 5backends-charge-mode.c
/* Select the callback location used by this displayed example. */
#define SELECTED_BACKEND_EXAMPLE 1backends-emit-mode.c
/* Select the callback location used by this displayed example. */
#define SELECTED_BACKEND_EXAMPLE 2backends-filter-mode.c
/* Select the callback location used by this displayed example. */
#define SELECTED_BACKEND_EXAMPLE 3backends-input-mode.c
/* Select the callback location used by this displayed example. */
#define SELECTED_BACKEND_EXAMPLE 4backends.c
#include <maelys/datalog.h>
#include <maelys/datalog_builders.h>
#include <maelys/datalog_backend.h>
#include <maelys/datalog_extension.h>
#include <maelys/datalog_resources.h>
#include <maelys/datalog_inputs.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
static int show_output = 1, cleanup_failed = 0;
static maelys_datalog_policy_t *policy = NULL, *context_policy = NULL;
static maelys_datalog_session_t *witness = NULL, *session5 = NULL, *session6 = NULL, *session7 = NULL;
static const maelys_datalog_program_t *witness_program = NULL;
static maelys_datalog_context_t *catalog = NULL;
static maelys_datalog_session_config_t *config = NULL;
static maelys_datalog_session_inputs_t *retained = NULL;
static maelys_datalog_result_t *result = NULL;
static maelys_datalog_diagnostic_t diagnostic;
static void *arena5 = NULL, *arena6 = NULL, *arena7 = NULL, *input_storage = NULL;
static size_t caller_acquires = 0, caller_releases = 0;
static const char policy_source[] =
"allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)), ends_with(Doc, \".pdf\").";
static const maelys_datalog_fact_t initial_inputs[] = {
{"user", 1, {MAELYS_DATALOG_SYMBOL("alice")}},
{"owns", 2, {MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf")}}
};
static const maelys_datalog_fact_t blocked_alice = {"blocked", 1, {MAELYS_DATALOG_SYMBOL("alice")}};
static void check_status(maelys_datalog_status_t status) {
if (status) { fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status)); exit(EXIT_FAILURE); }
}
static void report(const char *format, ...) {
if (!show_output) return;
va_list args; va_start(args, format); vprintf(format, args); va_end(args);
}
static void *aligned_storage(size_t bytes, size_t alignment) {
if (!alignment || alignment > _Alignof(max_align_t)) exit(EXIT_FAILURE);
void *p = malloc(bytes); if (!p) exit(EXIT_FAILURE); return p;
}
static void release_result(void) { check_status(maelys_datalog_result_free(result)); result = NULL; }
static void print_decision(const char *label) {
const maelys_datalog_value_t terms[] = {MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf")};
int allowed = 0;
check_status(maelys_datalog_result_query(result, "allow", terms, 2, &allowed));
report("%s: %s\n", label, allowed ? "allowed" : "denied");
}
static void cleanup(void) {
if (result) { if (maelys_datalog_result_free(result)) cleanup_failed = 1; result = NULL; }
if (retained) { if (maelys_datalog_session_inputs_free(retained)) cleanup_failed = 1; retained = NULL; }
if (config) { if (maelys_datalog_session_config_free(config)) cleanup_failed = 1; config = NULL; }
if (session7) { if (maelys_datalog_session_free(session7)) cleanup_failed = 1; session7 = NULL; }
if (session6) { if (maelys_datalog_session_free(session6)) cleanup_failed = 1; session6 = NULL; }
if (session5) { if (maelys_datalog_session_free(session5)) cleanup_failed = 1; session5 = NULL; }
if (witness) { if (maelys_datalog_session_free(witness)) cleanup_failed = 1; witness = NULL; }
if (context_policy) { if (maelys_datalog_policy_free(context_policy)) cleanup_failed = 1; context_policy = NULL; }
if (policy) { if (maelys_datalog_policy_free(policy)) cleanup_failed = 1; policy = NULL; }
if (catalog) { if (maelys_datalog_context_free(catalog)) cleanup_failed = 1; catalog = NULL; }
free(input_storage); input_storage = NULL;
free(arena7); arena7 = NULL; free(arena6); arena6 = NULL; free(arena5); arena5 = NULL;
}
/* Displayed fragments execute at the real output/input callback scope. */
static maelys_datalog_status_t run_selected_example(
maelys_datalog_backend_output_t *output,
const maelys_datalog_backend_input_view_t *view, size_t index,
const maelys_datalog_fact_t *answer, maelys_datalog_fact_t *out_fact,
const char *document, int *out_matched) {
/* API_REFERENCE_EXAMPLE */
}
/* This teaching backend accepts one normalized document-access rule, not arbitrary Datalog. */
#define BACKEND_FACT_LIMIT 16u
#define BACKEND_TEXT_LIMIT 64u
#define BACKEND_FEATURES (MAELYS_DATALOG_CAP_POSITIVE | MAELYS_DATALOG_CAP_NEGATION | MAELYS_DATALOG_CAP_FILTERS | MAELYS_DATALOG_CAP_WORK_LIMIT)
typedef struct {
char predicate[BACKEND_TEXT_LIMIT], terms[2][BACKEND_TEXT_LIMIT];
size_t arity;
} document_fact;
typedef struct { document_fact rows[BACKEND_FACT_LIMIT]; size_t count; } document_set;
typedef struct {
document_set facts;
maelys_datalog_input_base_t next;
int transaction, accepted;
} document_candidate;
typedef struct {
document_set committed, scratch;
document_set *workspace;
document_candidate candidate;
maelys_datalog_input_base_t base;
int has_base;
maelys_datalog_allocation_service_t allocation;
int service_inspected, workspace_fits, workspace_acquired;
size_t commits, aborts;
} document_backend_state;
static int variable(const maelys_datalog_ir_term_t *term, uint32_t number) {
return term->kind == MAELYS_DATALOG_IR_VARIABLE && term->as.variable == number;
}
static int atom(const maelys_datalog_ir_atom_t *value, const char *name, size_t arity,
uint32_t first, uint32_t second) {
return !strcmp(value->predicate, name) && value->arity == arity &&
variable(&value->terms[0], first) && (arity == 1 || variable(&value->terms[1], second));
}
static maelys_datalog_status_t accept_document_program(const maelys_datalog_program_t *program) {
maelys_datalog_program_info_t info;
maelys_datalog_status_t status = maelys_datalog_program_info(program, &info);
if (status) return status;
if (info.fact_count || info.rule_count != 1 || info.predicate_count != 4 ||
(info.required_capabilities & ~BACKEND_FEATURES)) return MAELYS_DATALOG_STATUS_UNSUPPORTED;
maelys_datalog_ir_rule_t rule;
status = maelys_datalog_program_rule(program, 0, &rule);
if (status) return status;
if (rule.expression_count || rule.body_count != 4 || !atom(&rule.head, "allow", 2, 0, 1) ||
rule.body[0].kind != MAELYS_DATALOG_IR_ATOM || !atom(&rule.body[0].atom, "user", 1, 0, 0) ||
rule.body[1].kind != MAELYS_DATALOG_IR_ATOM || !atom(&rule.body[1].atom, "owns", 2, 0, 1) ||
rule.body[2].kind != MAELYS_DATALOG_IR_NEGATION || !atom(&rule.body[2].atom, "blocked", 1, 0, 0) ||
rule.body[3].kind != MAELYS_DATALOG_IR_FILTER ||
strcmp(rule.body[3].filter_name, "ends_with") ||
strcmp(rule.body[3].filter_semantic_id, "string.ends-with.utf8-bytes-v1") ||
rule.body[3].pattern_length != 4 || memcmp(rule.body[3].pattern, ".pdf", 4) ||
!variable(&rule.body[3].filter_value, 1)) return MAELYS_DATALOG_STATUS_UNSUPPORTED;
const maelys_datalog_predicate_t expected[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2)
};
for (size_t i = 0; i < info.predicate_count; ++i) {
maelys_datalog_predicate_t actual;
status = maelys_datalog_program_predicate(program, i, &actual);
if (status) return status;
int found = 0;
for (size_t j = 0; j < 4; ++j)
if (!strcmp(actual.name, expected[j].name) && actual.arity == expected[j].arity &&
actual.flags == expected[j].flags) found = 1;
if (!found) return MAELYS_DATALOG_STATUS_UNSUPPORTED;
}
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t document_requirements(const maelys_datalog_program_t *program,
size_t *bytes, size_t *alignment) {
maelys_datalog_status_t status = accept_document_program(program);
if (status) return status;
*bytes = sizeof(document_backend_state); *alignment = _Alignof(document_backend_state);
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t document_prepare(const maelys_datalog_program_t *program,
const maelys_datalog_backend_storage_t *storage, void **out_state) {
size_t bytes, alignment;
maelys_datalog_status_t status = document_requirements(program, &bytes, &alignment);
if (status) return status;
if (!storage->bytes || storage->size < bytes || storage->alignment < alignment)
return MAELYS_DATALOG_STATUS_STORAGE_TOO_SMALL;
document_backend_state *state = storage->bytes;
memset(state, 0, sizeof(*state)); state->workspace = &state->scratch;
*out_state = state;
return MAELYS_DATALOG_STATUS_OK;
}
static void check_supported_program(void) {
check_status(accept_document_program(witness_program));
report("supported document policy: yes\n");
}
/* Copy strings: ABI 7 input views cannot be retained beyond the callback. */
static maelys_datalog_status_t copy_input(document_fact *out, const maelys_datalog_fact_t *input) {
size_t arity = !strcmp(input->predicate, "owns") ? 2 : 1;
if ((strcmp(input->predicate, "user") && strcmp(input->predicate, "owns") &&
strcmp(input->predicate, "blocked")) || input->arity != arity)
return MAELYS_DATALOG_STATUS_UNSUPPORTED;
if (strlen(input->predicate) >= sizeof(out->predicate)) return MAELYS_DATALOG_STATUS_UNSUPPORTED;
for (size_t i = 0; i < arity; ++i)
if (input->terms[i].kind != MAELYS_DATALOG_VALUE_SYMBOL ||
strlen(input->terms[i].as.symbol) >= sizeof(out->terms[i])) return MAELYS_DATALOG_STATUS_UNSUPPORTED;
strcpy(out->predicate, input->predicate); out->arity = arity;
for (size_t i = 0; i < arity; ++i) strcpy(out->terms[i], input->terms[i].as.symbol);
return MAELYS_DATALOG_STATUS_OK;
}
static int same_fact(const document_fact *left, const document_fact *right) {
return left->arity == right->arity && !strcmp(left->predicate, right->predicate) &&
!strcmp(left->terms[0], right->terms[0]) &&
(left->arity == 1 || !strcmp(left->terms[1], right->terms[1]));
}
static maelys_datalog_status_t add_fact(document_set *set, const document_fact *fact) {
for (size_t i = 0; i < set->count; ++i) if (same_fact(&set->rows[i], fact)) return MAELYS_DATALOG_STATUS_OK;
if (set->count == BACKEND_FACT_LIMIT) return MAELYS_DATALOG_STATUS_PAYLOAD_TOO_LARGE;
set->rows[set->count++] = *fact; return MAELYS_DATALOG_STATUS_OK;
}
static void remove_fact(document_set *set, const document_fact *fact) {
for (size_t i = 0; i < set->count; ++i) if (same_fact(&set->rows[i], fact)) {
memmove(&set->rows[i], &set->rows[i + 1], (set->count - i - 1) * sizeof(set->rows[0]));
--set->count; return;
}
}
static maelys_datalog_status_t has_user(const document_set *set, const char *predicate,
const char *user, maelys_datalog_backend_output_t *output, int *present) {
*present = 0;
for (size_t i = 0; i < set->count; ++i) {
maelys_datalog_status_t status = maelys_datalog_backend_charge(output, 1);
if (status) return status;
if (!strcmp(set->rows[i].predicate, predicate) && !strcmp(set->rows[i].terms[0], user)) {
*present = 1; break;
}
}
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t emit_document_answers(const document_set *set,
maelys_datalog_backend_output_t *output) {
for (size_t i = 0; i < set->count; ++i) {
maelys_datalog_status_t status = maelys_datalog_backend_charge(output, 1);
if (status) return status;
const document_fact *owner = &set->rows[i];
if (strcmp(owner->predicate, "owns")) continue;
int user, blocked, pdf;
status = has_user(set, "user", owner->terms[0], output, &user); if (status) return status;
status = has_user(set, "blocked", owner->terms[0], output, &blocked); if (status) return status;
if (!user || blocked) continue;
#if SELECTED_BACKEND_EXAMPLE == 3
status = run_selected_example(output, NULL, 0, NULL, NULL, owner->terms[1], &pdf);
#else
status = maelys_datalog_backend_filter(output, "ends_with", "string.ends-with.utf8-bytes-v1",
(const unsigned char *)owner->terms[1], strlen(owner->terms[1]),
(const unsigned char *)".pdf", 4, &pdf);
#endif
if (status) return status;
if (pdf) {
const maelys_datalog_fact_t answer = {"allow", 2,
{MAELYS_DATALOG_SYMBOL(owner->terms[0]), MAELYS_DATALOG_SYMBOL(owner->terms[1])}};
#if SELECTED_BACKEND_EXAMPLE == 2
status = run_selected_example(output, NULL, 0, &answer, NULL, NULL, NULL);
#else
status = maelys_datalog_backend_emit(output, &answer);
#endif
if (status) return status;
}
}
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t document_snapshot(void *opaque, const maelys_datalog_fact_t *inputs,
size_t count, maelys_datalog_backend_output_t *output, void **out_result,
maelys_datalog_diagnostic_t *diagnostic) {
(void)diagnostic;
document_backend_state *state = opaque;
*out_result = &state->candidate; state->candidate.transaction = 0; state->candidate.accepted = 0;
#if SELECTED_BACKEND_EXAMPLE == 1
maelys_datalog_status_t example_status = run_selected_example(output, NULL, 0, NULL, NULL, NULL, NULL);
if (example_status) return example_status;
#endif
state->workspace->count = 0;
for (size_t i = 0; i < count; ++i) {
maelys_datalog_status_t status = maelys_datalog_backend_charge(output, 1);
if (status) return status;
document_fact owned; status = copy_input(&owned, &inputs[i]); if (status) return status;
status = add_fact(state->workspace, &owned); if (status) return status;
}
return emit_document_answers(state->workspace, output);
}
static void document_commit(void *opaque, void *result) {
document_backend_state *state = opaque; document_candidate *candidate = result;
if (candidate->transaction) { state->committed = candidate->facts; state->base = candidate->next; state->has_base = 1; }
candidate->accepted = 1; ++state->commits;
}
static void document_release_result(void *opaque, void *result) {
document_backend_state *state = opaque; document_candidate *candidate = result;
if (!candidate->accepted) ++state->aborts;
/* Embedded candidate storage is reused after the result lease ends. */
}
static void document_destroy(void *opaque) {
document_backend_state *state = opaque;
if (state->workspace_acquired) state->allocation.release(state->allocation.context, state->workspace);
}
static void describe_output_contract(void) {
report("output: complete allow relation; work and filter errors propagate\n");
}
static const maelys_datalog_backend_t documents_v5 = {
.abi_version = MAELYS_DATALOG_BACKEND_ABI_VERSION, .struct_size = sizeof(documents_v5),
.name = "documents_v5", .semantic_id = "example.documents.fixed-snapshot.v1",
.capabilities = BACKEND_FEATURES, .storage_requirements = document_requirements,
.prepare = document_prepare, .solve = document_snapshot,
.commit = document_commit, .destroy_result = document_release_result, .destroy = document_destroy
};
static void register_and_run_snapshot(void) {
const maelys_datalog_extension_t bundle = {
.abi_version = MAELYS_DATALOG_EXTENSION_ABI_VERSION, .struct_size = sizeof(bundle),
.name = "document_backends", .semantic_id = "example.document-backends.v1",
.backends = &documents_v5, .backend_count = 1
};
check_status(maelys_datalog_context_create(&catalog));
check_status(maelys_datalog_context_register(catalog, &bundle));
check_status(maelys_datalog_context_seal(catalog, NULL));
check_status(maelys_datalog_context_load_inline(catalog, NULL, "backend_documents", "documents",
policy_source, strlen(policy_source), &context_policy, &diagnostic));
check_status(maelys_datalog_session_config_create(&config));
check_status(maelys_datalog_session_config_set_context(config, catalog, documents_v5.name));
size_t bytes, alignment;
check_status(maelys_datalog_backend_storage_requirements(context_policy, 0, &documents_v5, &bytes, &alignment));
arena5 = aligned_storage(bytes, alignment);
const maelys_datalog_backend_storage_t storage = {sizeof(storage), arena5, bytes, alignment};
check_status(maelys_datalog_session_config_set_backend_storage(config, &storage));
check_status(maelys_datalog_session_create_configured(context_policy, 0, config, &session5));
check_status(maelys_datalog_session_solve(session5, initial_inputs, 2, &result, &diagnostic));
print_decision("ABI 5 snapshot, alice"); release_result();
check_status(maelys_datalog_session_config_free(config)); config = NULL;
}
static void *caller_acquire(void *context, size_t bytes, size_t alignment) {
(void)context;
if (alignment > _Alignof(max_align_t)) return NULL;
void *p = malloc(bytes); if (p) ++caller_acquires; return p;
}
static void caller_release(void *context, void *pointer, size_t bytes, size_t alignment) {
(void)context; (void)bytes; (void)alignment; ++caller_releases; free(pointer);
}
static const maelys_datalog_caller_allocator_t caller_allocator = {
.struct_size = sizeof(caller_allocator), .contract_version = MAELYS_DATALOG_CALLER_ALLOCATOR_VERSION,
.acquire = caller_acquire, .release = caller_release
};
static maelys_datalog_status_t document_resource_requirements(const maelys_datalog_program_t *program,
const maelys_datalog_session_resources_t *resources, size_t *bytes, size_t *alignment) {
maelys_datalog_status_t status = document_requirements(program, bytes, alignment);
if (status) return status;
if (resources->struct_size < MAELYS_DATALOG_RESOURCES_V1_SIZE ||
resources->contract_version != MAELYS_DATALOG_RESOURCE_CONTRACT_VERSION ||
(resources->required_features & ~MAELYS_DATALOG_RESOURCE_SUPPORTED) ||
(resources->memory_mode != MAELYS_DATALOG_MEMORY_FIXED &&
resources->memory_mode != MAELYS_DATALOG_MEMORY_BACKEND_ELASTIC) ||
resources->input_facts > BACKEND_FACT_LIMIT || resources->derived_facts > BACKEND_FACT_LIMIT)
return MAELYS_DATALOG_STATUS_UNSUPPORTED;
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t document_resource_prepare(const maelys_datalog_program_t *program,
const maelys_datalog_session_resources_t *resources, const maelys_datalog_backend_storage_t *storage,
void **out_state) {
size_t bytes, alignment;
maelys_datalog_status_t status = document_resource_requirements(program, resources, &bytes, &alignment);
if (status) return status;
status = document_prepare(program, storage, out_state); if (status) return status;
if (resources->memory_mode == MAELYS_DATALOG_MEMORY_BACKEND_ELASTIC) {
if (resources->struct_size < sizeof(maelys_datalog_session_allocation_resources_t))
return MAELYS_DATALOG_STATUS_UNSUPPORTED;
const maelys_datalog_session_allocation_resources_t *extended = (const void *)resources;
const maelys_datalog_allocation_service_t *service = extended->allocation;
if (!service || service->struct_size < MAELYS_DATALOG_ALLOCATION_SERVICE_V1_SIZE ||
service->contract_version != MAELYS_DATALOG_ALLOCATION_SERVICE_VERSION ||
service->reserved || service->required_features || !service->inspect ||
!service->acquire || !service->release || service->maximum_alignment < _Alignof(document_set))
return MAELYS_DATALOG_STATUS_UNSUPPORTED;
document_backend_state *state = *out_state; state->allocation = *service;
maelys_datalog_allocation_budget_t budget = MAELYS_DATALOG_ALLOCATION_BUDGET_INIT;
status = state->allocation.inspect(state->allocation.context, sizeof(document_set),
_Alignof(document_set), &budget); if (status) return status;
state->service_inspected = 1; state->workspace_fits = budget.fits;
if (!budget.fits) return MAELYS_DATALOG_STATUS_PAYLOAD_TOO_LARGE;
void *block = NULL;
status = state->allocation.acquire(state->allocation.context, sizeof(document_set),
_Alignof(document_set), &block, NULL); if (status) return status;
state->workspace = block; state->workspace_acquired = 1; memset(state->workspace, 0, sizeof(*state->workspace));
}
return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_backend_v6_t documents_v6 = {
.abi_version = MAELYS_DATALOG_BACKEND_V6_ABI_VERSION, .struct_size = sizeof(documents_v6),
.name = "documents_v6", .semantic_id = "example.documents.resource-snapshot.v1",
.capabilities = BACKEND_FEATURES,
.resource_features = MAELYS_DATALOG_RESOURCE_SESSION_CAPACITIES | MAELYS_DATALOG_RESOURCE_CALLER_ALLOCATOR,
.storage_requirements = document_resource_requirements, .prepare = document_resource_prepare,
.solve = document_snapshot, .commit = document_commit,
.destroy_result = document_release_result, .destroy = document_destroy
};
static void run_with_resources(void) {
check_status(maelys_datalog_session_config_create(&config));
check_status(maelys_datalog_session_config_set_backend_v6(config, &documents_v6));
arena6 = aligned_storage(sizeof(document_backend_state), _Alignof(document_backend_state));
const maelys_datalog_backend_storage_t storage = {sizeof(storage), arena6, sizeof(document_backend_state), _Alignof(document_backend_state)};
check_status(maelys_datalog_session_config_set_backend_storage(config, &storage));
maelys_datalog_session_allocation_request_t request = MAELYS_DATALOG_ALLOCATION_REQUEST_INIT;
request.base.capacity_mask = MAELYS_DATALOG_CAPACITY_INPUT_FACTS | MAELYS_DATALOG_CAPACITY_DERIVED_FACTS;
request.base.input_facts = BACKEND_FACT_LIMIT; request.base.derived_facts = BACKEND_FACT_LIMIT;
request.execution_byte_cap = 16u * 1024u * 1024u; request.allocator = &caller_allocator;
check_status(maelys_datalog_session_config_set_resources(config, &request.base));
check_status(maelys_datalog_session_create_configured(policy, 0, config, &session6));
document_backend_state *state = arena6;
report("ABI 6 host allocation service inspected: %s\n", state->service_inspected ? "yes" : "no");
report("workspace fits the session budget: %s\n", state->workspace_fits ? "yes" : "no");
check_status(maelys_datalog_session_solve(session6, initial_inputs, 2, &result, &diagnostic));
print_decision("ABI 6 snapshot, alice"); release_result();
check_status(maelys_datalog_session_config_free(config)); config = NULL;
}
static int same_base(maelys_datalog_input_base_t left, maelys_datalog_input_base_t right) {
return left.incarnation == right.incarnation && left.generation == right.generation;
}
static maelys_datalog_status_t apply_view(document_set *set,
const maelys_datalog_backend_input_view_t *view, size_t count, int removing,
maelys_datalog_backend_output_t *output) {
for (size_t i = 0; i < count; ++i) {
maelys_datalog_status_t status = maelys_datalog_backend_charge(output, 1);
if (status) return status;
maelys_datalog_fact_t borrowed;
#if SELECTED_BACKEND_EXAMPLE == 4
status = run_selected_example(output, view, i, NULL, &borrowed, NULL, NULL);
#else
status = maelys_datalog_backend_input_at(view, i, &borrowed);
#endif
if (status) return status;
document_fact owned; status = copy_input(&owned, &borrowed); if (status) return status;
if (removing) remove_fact(set, &owned);
else { status = add_fact(set, &owned); if (status) return status; }
}
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t document_transaction(void *opaque,
const maelys_datalog_backend_input_t *input, maelys_datalog_backend_output_t *output,
void **out_result, maelys_datalog_diagnostic_t *diagnostic) {
(void)diagnostic;
document_backend_state *state = opaque;
*out_result = &state->candidate; state->candidate.transaction = 1; state->candidate.accepted = 0;
if ((state->has_base && !same_base(input->base, state->base)) ||
(!state->has_base && input->base.generation != 0)) return MAELYS_DATALOG_STATUS_INVALID_STATE;
document_set *candidate = &state->candidate.facts;
if (input->kind == MAELYS_DATALOG_BACKEND_INPUT_REPLACE) candidate->count = 0;
else if (input->kind == MAELYS_DATALOG_BACKEND_INPUT_DELTA) *candidate = state->committed;
else return MAELYS_DATALOG_STATUS_UNSUPPORTED;
maelys_datalog_status_t status = apply_view(candidate, input->removals, input->removal_count, 1, output);
if (status) return status;
status = apply_view(candidate, input->additions, input->addition_count, 0, output);
if (status) return status;
state->candidate.next = input->next;
/* Only commit copies candidate facts and adopts next; failure leaves live state intact. */
return emit_document_answers(candidate, output);
}
static const maelys_datalog_backend_v7_t documents_v7 = {
.abi_version = MAELYS_DATALOG_BACKEND_V7_ABI_VERSION, .struct_size = sizeof(documents_v7),
.name = "documents_v7", .semantic_id = "example.documents.retained-transactions.v1",
.capabilities = BACKEND_FEATURES, .resource_features = MAELYS_DATALOG_RESOURCE_SESSION_CAPACITIES,
.storage_requirements = document_resource_requirements, .prepare = document_resource_prepare,
.solve = document_transaction, .commit = document_commit,
.destroy_result = document_release_result, .destroy = document_destroy
};
static void describe_transaction_contract(void) {
report("ABI 7 packets: replace or delta; borrowed facts copied; next adopted in commit\n");
}
static void run_retained_inputs(void) {
check_status(maelys_datalog_session_config_create(&config));
/* ABI 7 is selected directly; v0.26 has no ABI 7 extension registry. */
check_status(maelys_datalog_session_config_set_backend_v7(config, &documents_v7));
check_status(maelys_datalog_session_config_set_work_limit(config, 18));
arena7 = aligned_storage(sizeof(document_backend_state), _Alignof(document_backend_state));
const maelys_datalog_backend_storage_t storage = {sizeof(storage), arena7, sizeof(document_backend_state), _Alignof(document_backend_state)};
check_status(maelys_datalog_session_config_set_backend_storage(config, &storage));
maelys_datalog_session_resource_request_t request = MAELYS_DATALOG_RESOURCE_REQUEST_INIT;
request.capacity_mask = MAELYS_DATALOG_CAPACITY_INPUT_FACTS | MAELYS_DATALOG_CAPACITY_DERIVED_FACTS;
request.input_facts = BACKEND_FACT_LIMIT; request.derived_facts = BACKEND_FACT_LIMIT;
check_status(maelys_datalog_session_config_set_resources(config, &request));
check_status(maelys_datalog_session_create_configured(policy, 0, config, &session7));
maelys_datalog_input_options_t options = MAELYS_DATALOG_INPUT_OPTIONS_INIT;
const char *const symbols[] = {"alice", "roadmap.pdf"};
options.fact_capacity = BACKEND_FACT_LIMIT; options.addition_capacity = 4; options.removal_capacity = 4;
options.symbols = symbols; options.symbol_count = 2;
size_t bytes, alignment;
check_status(maelys_datalog_session_inputs_storage_requirements(session7, &options, &bytes, &alignment));
input_storage = aligned_storage(bytes, alignment);
check_status(maelys_datalog_session_inputs_init(session7, &options, input_storage, bytes, &retained));
maelys_datalog_input_base_t base;
check_status(maelys_datalog_session_inputs_base(retained, &base));
check_status(maelys_datalog_session_inputs_replace(retained, base, initial_inputs, 2, &result, &diagnostic));
print_decision("ABI 7 replace, alice"); release_result();
check_status(maelys_datalog_session_inputs_base(retained, &base));
check_status(maelys_datalog_session_inputs_apply(retained, base, &blocked_alice, 1, NULL, 0, &result, &diagnostic));
print_decision("ABI 7 delta after blocking alice"); release_result();
document_backend_state *state = arena7;
check_status(maelys_datalog_session_inputs_base(retained, &base));
report("host and backend committed bases agree: %s\n", same_base(base, state->base) ? "yes" : "no");
check_status(maelys_datalog_session_config_free(config)); config = NULL;
}
static void check_limits_and_release(void) {
maelys_datalog_input_base_t before, after;
check_status(maelys_datalog_session_inputs_base(retained, &before));
const maelys_datalog_fact_t more_inputs[] = {
{"user", 1, {MAELYS_DATALOG_SYMBOL("roadmap.pdf")}},
{"owns", 2, {MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("alice")}},
{"owns", 2, {MAELYS_DATALOG_SYMBOL("roadmap.pdf"), MAELYS_DATALOG_SYMBOL("alice")}},
{"owns", 2, {MAELYS_DATALOG_SYMBOL("roadmap.pdf"), MAELYS_DATALOG_SYMBOL("roadmap.pdf")}}
};
document_backend_state *state = arena7;
const size_t commits = state->commits, aborts = state->aborts;
const document_set committed = state->committed;
maelys_datalog_status_t status = maelys_datalog_session_inputs_apply(
retained, before, more_inputs, 4, &blocked_alice, 1, &result, &diagnostic);
report("over-budget transaction: %s\n", maelys_datalog_status_name(status));
if (status != MAELYS_DATALOG_STATUS_PAYLOAD_TOO_LARGE || result) exit(EXIT_FAILURE);
check_status(maelys_datalog_session_inputs_base(retained, &after));
int intact = same_base(before, after) && same_base(before, state->base) &&
state->commits == commits && state->aborts == aborts + 1 &&
committed.count == state->committed.count;
for (size_t i = 0; intact && i < committed.count; ++i)
intact = same_fact(&committed.rows[i], &state->committed.rows[i]);
report("failed candidate left committed facts and base intact: %s\n", intact ? "yes" : "no");
if (!intact) exit(EXIT_FAILURE);
check_status(maelys_datalog_session_inputs_apply(retained, before, NULL, 0, NULL, 0, &result, &diagnostic));
print_decision("retry from the unchanged base, alice"); release_result();
maelys_datalog_policy_t *changed = NULL;
const char changed_source[] =
"allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)), ends_with(Doc, \".pdf\").\n"
"allow(User, Doc) :- owns(User, Doc), blocked(User).";
check_status(maelys_datalog_policy_load_inline("backend_documents", "unsupported-shape",
changed_source, sizeof(changed_source) - 1, &changed, &diagnostic));
size_t bytes = 0, alignment = 0;
status = maelys_datalog_backend_storage_requirements(changed, 0, &documents_v5, &bytes, &alignment);
report("unimplemented policy shape: %s\n", maelys_datalog_status_name(status));
if (status != MAELYS_DATALOG_STATUS_UNSUPPORTED) exit(EXIT_FAILURE);
check_status(maelys_datalog_policy_free(changed));
status = maelys_datalog_session_solve(session7, initial_inputs, 2, &result, &diagnostic);
report("ordinary snapshot while retained inputs are attached: %s\n", maelys_datalog_status_name(status));
if (status != MAELYS_DATALOG_STATUS_INVALID_STATE || result) exit(EXIT_FAILURE);
check_status(maelys_datalog_session_inputs_free(retained)); retained = NULL;
free(input_storage); input_storage = NULL;
check_status(maelys_datalog_session_free(session7)); session7 = NULL;
check_status(maelys_datalog_session_free(session6)); session6 = NULL;
report("caller allocation requests released: %s\n", caller_acquires == caller_releases ? "yes" : "no");
check_status(maelys_datalog_session_free(session5)); session5 = NULL;
check_status(maelys_datalog_session_free(witness)); witness = NULL; witness_program = NULL;
check_status(maelys_datalog_policy_free(policy)); policy = NULL;
check_status(maelys_datalog_policy_free(context_policy)); context_policy = NULL;
check_status(maelys_datalog_context_free(catalog)); catalog = NULL;
report("released: results, retained inputs, sessions, policies and context\n");
}
static void bootstrap(void) {
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2)
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("backend_documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
check_status(maelys_datalog_policy_load_inline("backend_documents", "documents", policy_source,
strlen(policy_source), &policy, &diagnostic));
check_status(maelys_datalog_session_create(policy, 0, &witness));
check_status(maelys_datalog_session_program(witness, &witness_program));
}
int main(void) {
if (atexit(cleanup) != 0) return EXIT_FAILURE;
diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
bootstrap();
show_output = 0;
#if SELECTED_BACKEND_EXAMPLE == 4
run_retained_inputs();
#elif SELECTED_BACKEND_EXAMPLE == 5
check_status(run_selected_example(NULL, NULL, 0, NULL, NULL, NULL, NULL));
#else
register_and_run_snapshot();
#endif
cleanup();
return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}decisions.c
/* Decisions use already checked presence bits, with no session or policy setup. */
static void cleanup_context(void) {}
int main(void) {
{
/* API_REFERENCE_EXAMPLE */
}
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}edb.c
/* Runtime EDB extension of the common C reference declarations. */
static maelys_datalog_input_edb_t *edb = NULL;
/* Idempotent: normal completion and check_status failure use the same cleanup. */
static void cleanup_context(void) {
if (edb != NULL) {
maelys_datalog_status_t status = maelys_datalog_input_edb_free(edb);
edb = NULL;
cleanup_status(status);
}
}
static size_t fact_count(maelys_datalog_input_edb_t *edb) {
size_t count = 0;
check_status(maelys_datalog_input_edb_count(edb, &count));
return count;
}
static void add_user(maelys_datalog_input_edb_t *edb, maelys_datalog_diagnostic_t *diagnostic) {
const maelys_datalog_value_t terms[] = { MAELYS_DATALOG_SYMBOL("alice") };
check_status(maelys_datalog_input_edb_add_fact(edb, "user", terms, 1u, diagnostic));
}
static void *allocate_storage(size_t bytes, size_t alignment) {
void *storage = malloc(bytes);
if (storage == NULL || alignment == 0 || (uintptr_t)storage % alignment != 0) {
free(storage);
fputs("Storage allocation failed\n", stderr);
exit(EXIT_FAILURE);
}
return storage;
}
int main(void) {
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("enabled", 1),
};
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
maelys_datalog_diagnostic_t diagnostic_value = MAELYS_DATALOG_DIAGNOSTIC_INIT;
maelys_datalog_diagnostic_t *diagnostic = &diagnostic_value;
check_status(maelys_datalog_input_edb_create(&edb));
const maelys_datalog_fact_t facts[] = {
{"user", 1u, { MAELYS_DATALOG_SYMBOL("alice") }},
{"owns", 2u, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") }},
};
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}errors.c
/* Page extension: preserves this page’s reviewed document-access scenario. */
static void cleanup_context(void) {
}
/* Page reference context for diagnostic and limit calls; no engine objects are needed. */
static maelys_datalog_diagnostic_t failed_diagnostic(void) {
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
maelys_datalog_policy_t *policy = NULL;
const char *source = "allow(User, Doc) :- owns(User, Doc).";
maelys_datalog_status_t status = maelys_datalog_policy_load_inline(
"missing-domain", "documents.main", source, strlen(source), &policy, &diagnostic);
if (status == MAELYS_DATALOG_STATUS_OK) {
check_status(maelys_datalog_policy_free(policy));
fputs("Expected policy loading to fail\n", stderr);
exit(EXIT_FAILURE);
}
return diagnostic;
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
/* API_REFERENCE_EXAMPLE */
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}event-windows.c
/* Event windows borrow two idle sessions; each adapter has its own pair. */
#include <maelys/datalog_window.h>
#include <stdint.h>
#include <inttypes.h>
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *sessions[4] = { NULL, NULL, NULL, NULL };
static maelys_datalog_window_t *window = NULL;
static maelys_datalog_group_window_t *group_window = NULL;
static void *window_storage = NULL, *group_storage = NULL;
static const size_t event_capacity = 2, text_capacity = 512;
static const maelys_datalog_group_window_capacities_t capacities = { 2, 8, 8, 512 };
static const maelys_datalog_window_options_t options = {
sizeof(maelys_datalog_window_options_t), 4, MAELYS_DATALOG_WINDOW_EXPIRATION
};
static const maelys_datalog_value_t terms[] = {
MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf")
};
static const maelys_datalog_fact_t facts[] = {
{ "owns", 2, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") } },
{ "blocked", 1, { MAELYS_DATALOG_SYMBOL("mallory") } }
};
static const maelys_datalog_fact_t static_facts[] = {
{ "user", 1, { MAELYS_DATALOG_SYMBOL("alice") } }
};
static void cleanup_context(void) {
if (window != NULL) {
maelys_datalog_status_t status = maelys_datalog_window_free(window);
cleanup_status(status);
if (status != MAELYS_DATALOG_STATUS_OK) return;
window = NULL;
}
if (group_window != NULL) {
maelys_datalog_status_t status = maelys_datalog_group_window_free(group_window);
cleanup_status(status);
if (status != MAELYS_DATALOG_STATUS_OK) return;
group_window = NULL;
}
for (size_t i = 0; i < 4; ++i) {
if (sessions[i] != NULL) { cleanup_status(maelys_datalog_session_free(sessions[i])); sessions[i] = NULL; }
}
free(window_storage); window_storage = NULL;
free(group_storage); group_storage = NULL;
if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
}
static void *allocate_storage(size_t bytes, size_t alignment) {
void *storage = malloc(bytes);
if (storage == NULL || alignment == 0 || (uintptr_t)storage % alignment != 0) {
free(storage); fputs("Storage allocation failed\n", stderr); exit(EXIT_FAILURE);
}
return storage;
}
static void create_window(void) {
size_t bytes = 0, alignment = 0;
check_status(maelys_datalog_window_storage_requirements_configured(
event_capacity, text_capacity, &options, &bytes, &alignment));
window_storage = allocate_storage(bytes, alignment);
check_status(maelys_datalog_window_init_configured(window_storage, bytes,
event_capacity, text_capacity, &options, 0, sessions[0], sessions[1], &window, NULL));
}
static void create_group_window(void) {
size_t bytes = 0, alignment = 0;
check_status(maelys_datalog_group_window_storage_requirements_configured(
&capacities, &options, &bytes, &alignment));
group_storage = allocate_storage(bytes, alignment);
check_status(maelys_datalog_group_window_init_configured(group_storage, bytes,
&capacities, &options, 0, sessions[2], sessions[3], &group_window, NULL));
}
static void populate_window(void) {
create_window();
check_status(maelys_datalog_window_push_until(window, "access", terms, 2, 10, NULL, NULL));
check_status(maelys_datalog_window_push_until(window, "access", terms, 2, 20, NULL, NULL));
}
static void populate_group_window(void) {
create_group_window();
check_status(maelys_datalog_group_window_push_until(group_window, facts,
sizeof(facts) / sizeof(facts[0]), 10, NULL, NULL));
check_status(maelys_datalog_group_window_push_until(group_window, facts,
sizeof(facts) / sizeof(facts[0]), 20, NULL, NULL));
}
static size_t observed_count(maelys_datalog_result_t *result) {
maelys_datalog_fact_view_t rows[2];
size_t count = 0;
check_status(maelys_datalog_result_enumerate(result, "observed", 2, rows, 2, &count));
return count;
}
static int allows_alice(maelys_datalog_result_t *result) {
int present = 0;
check_status(maelys_datalog_result_query(result, "allow", terms, 2, &present));
return present;
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_EDB("access", 3),
MAELYS_DATALOG_IDB_QUERY("allow", 2), MAELYS_DATALOG_IDB_QUERY("observed", 2)
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "allow(User, Doc) :- owns(User, Doc), not(blocked(User)).\n"
"observed(User, Doc) :- access(Occurrence, User, Doc).";
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("documents", "event-windows-context",
source, strlen(source), &policy, &diagnostic));
for (size_t i = 0; i < 4; ++i) check_status(maelys_datalog_session_create(policy, 0, &sessions[i]));
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}frontend.c
#include <maelys/datalog_frontend.h>
#include <maelys/datalog_builders.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static maelys_datalog_policy_t *policy = NULL;
static int cleanup_failed = 0;
static void check_status(maelys_datalog_status_t status) {
if (status != MAELYS_DATALOG_STATUS_OK) {
fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status));
exit(EXIT_FAILURE);
}
}
static void cleanup_context(void) {
if (policy) { if (maelys_datalog_policy_free(policy)) cleanup_failed = 1; policy = NULL; }
}
static const maelys_datalog_ir_atom_t atom = {
.predicate = "approved", .arity = 1,
.terms = {{.kind = MAELYS_DATALOG_IR_SYMBOL, .as.symbol = "alice"}}
};
static const maelys_datalog_ir_rule_t rule = {
.head = {.predicate = "allow", .arity = 1,
.terms = {{.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 0}}},
.body_count = 1,
.body = {{.kind = MAELYS_DATALOG_IR_ATOM, .atom = {.predicate = "approved", .arity = 1,
.terms = {{.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 0}}}}}
};
static maelys_datalog_status_t lower(const char *source, size_t length,
maelys_datalog_program_builder_t *builder, maelys_datalog_diagnostic_t *diagnostic) {
(void)source; (void)length; (void)diagnostic;
/* API_REFERENCE_EXAMPLE */
return MAELYS_DATALOG_STATUS_OK;
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_POLICY_FACT("approved", 1), MAELYS_DATALOG_IDB_QUERY("allow", 1)
};
const char *const atoms[] = {"alice"};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_WITH_ATOMS("frontend_cards", predicates, atoms);
check_status(maelys_datalog_domain_register(&domain));
const maelys_datalog_frontend_t frontend = {
MAELYS_DATALOG_PROGRAM_ABI_VERSION, sizeof(frontend), "cards", "example.cards.v1", lower
};
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
const char source[] = "cards";
check_status(maelys_datalog_policy_load_frontend("frontend_cards", "cards", source, strlen(source), &frontend, &policy, &diagnostic));
cleanup_context();
return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}manifest.c
/* Page extension: preserves this page’s reviewed document-access scenario. */
static maelys_datalog_policy_t *policy = NULL;
static void cleanup_context(void) {
if (policy != NULL) {
cleanup_status(maelys_datalog_policy_free(policy));
policy = NULL;
}
(void)remove("documents.dl");
(void)remove("manifest.json");
}
/* Page reference context; source policy and vocabulary from the public document-access guides. */
static int write_file(const char *path, const char *text) {
FILE *file = fopen(path, "wb");
if (file == NULL) return 0;
size_t length = strlen(text);
int written = fwrite(text, 1, length, file) == length;
int closed = fclose(file) == 0;
return written && closed;
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("delegated", 2), MAELYS_DATALOG_EDB("blocked", 1),
MAELYS_DATALOG_IDB("can_read", 2), MAELYS_DATALOG_IDB_QUERY("has_any_document", 1),
MAELYS_DATALOG_IDB_QUERY("allow", 2),
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "can_read(User, Doc) :-\n owns(User, Doc) or delegated(User, Doc),\n not(blocked(User)).\nhas_any_document(User) :- owns(User, _).\nallow(User, Doc) :- user(User), can_read(User, Doc).\n";
const char *manifest_json = "{\"policy_set_id\":\"documents\",\"policy_set_version\":\"1.0.0\",\"manifest_version\":\"1\",\"default_profile\":\"enforce\",\"created_for\":\"production\",\"strict_loading\":true,\"fail_closed\":true,\"capabilities\":[],\"policies\":[{\"policy_id\":\"documents.main\",\"domain\":\"documents\",\"file\":\"documents.dl\",\"sha256\":\"be25aa04e2c75e77012c60b1c36c80d5f651371d3887c851d1e0d74975de329a\",\"mode\":\"enforce\",\"enabled\":true,\"description\":\"Document access\",\"queries\":[{\"name\":\"allow\",\"arity\":2},{\"name\":\"has_any_document\",\"arity\":1}]}]}";
/* The historical text loader accepts MAELYS-DATALOG-v2 as its profile. */
const char profile_field[] = "\"default_profile\":\"enforce\"";
const char *profile = strstr(manifest_json, profile_field);
if (profile == NULL) return EXIT_FAILURE;
char historical_manifest_json[strlen(manifest_json) + sizeof("MAELYS-DATALOG-v2")];
int historical_length = snprintf(historical_manifest_json, sizeof(historical_manifest_json),
"%.*s\"default_profile\":\"MAELYS-DATALOG-v2\"%s",
(int)(profile - manifest_json), manifest_json, profile + strlen(profile_field));
if (historical_length < 0 || (size_t)historical_length >= sizeof(historical_manifest_json)) return EXIT_FAILURE;
if (!write_file("documents.dl", source) || !write_file("manifest.json", manifest_json)) {
fputs("reference file creation failed\n", stderr);
return EXIT_FAILURE;
}
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}module-builder.c
#include <maelys/datalog.h>
#include <maelys/datalog_builders.h>
#include <maelys/datalog_module.h>
#include <maelys/datalog_program.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_result_t *result = NULL;
static int cleanup_failed = 0;
static void check_status(maelys_datalog_status_t status) {
if (status != MAELYS_DATALOG_STATUS_OK) {
fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status));
exit(EXIT_FAILURE);
}
}
static void cleanup_context(void) {
if (result) { if (maelys_datalog_result_free(result)) cleanup_failed = 1; result = NULL; }
if (session) { if (maelys_datalog_session_free(session)) cleanup_failed = 1; session = NULL; }
if (policy) { if (maelys_datalog_policy_free(policy)) cleanup_failed = 1; policy = NULL; }
}
/* The filter is pure and bounded. No callback keeps pointers or calls the engine. */
static maelys_datalog_status_t validate_suffix(const unsigned char *pattern, size_t length) {
if (!pattern || !length || length > 63) return MAELYS_DATALOG_STATUS_INVALID_FIELD;
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t suffix_cost(size_t value_length, size_t pattern_length, size_t *out_cost) {
(void)value_length;
if (!out_cost) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
if (pattern_length == SIZE_MAX) return MAELYS_DATALOG_STATUS_PAYLOAD_TOO_LARGE;
*out_cost = pattern_length + 1;
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t evaluate_suffix(const unsigned char *value, size_t value_length,
const unsigned char *pattern, size_t pattern_length, int *out_matched) {
if (!value || !pattern || !out_matched) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
*out_matched = value_length >= pattern_length &&
memcmp(value + value_length - pattern_length, pattern, pattern_length) == 0;
return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_filter_module_t suffix_module = {
MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_filter_module_t),
"document_suffix", "example.document-suffix.bytes-v1.cost-pattern-plus-one",
validate_suffix, suffix_cost, evaluate_suffix
};
/* The core supplies only safe choices; this callback never reorders the array. */
static maelys_datalog_status_t choose_join(const maelys_datalog_join_candidate_t *candidates,
size_t candidate_count, size_t *out_candidate_index) {
if (!candidates || !candidate_count || !out_candidate_index)
return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
size_t best = 0;
for (size_t i = 1; i < candidate_count; ++i)
if (candidates[i].default_score > candidates[best].default_score ||
(candidates[i].default_score == candidates[best].default_score &&
candidates[i].body_index < candidates[best].body_index)) best = i;
*out_candidate_index = best;
return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_planner_module_t planner_module = {
MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_planner_module_t),
"document_join", "example.document-join.score-then-body-v1", choose_join
};
static const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2)
};
static maelys_datalog_status_t install_document_predicates(maelys_datalog_domain_builder_t *builder) {
for (size_t i = 0; i < 3; ++i)
check_status(maelys_datalog_domain_builder_add(builder, &predicates[i]));
/* API_REFERENCE_EXAMPLE */
}
static const char *const atoms[] = { ".pdf" };
static const maelys_datalog_domain_t domain = {
"document_modules", NULL, 0, atoms, sizeof(atoms) / sizeof(atoms[0])
};
static const char source[] =
"allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)), "
"document_suffix(Doc, \".pdf\").\n";
static const maelys_datalog_fact_t facts[] = {
{ "user", 1, { MAELYS_DATALOG_SYMBOL("alice") } },
{ "user", 1, { MAELYS_DATALOG_SYMBOL("mallory") } },
{ "owns", 2, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") } },
{ "owns", 2, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("draft.txt") } },
{ "owns", 2, { MAELYS_DATALOG_SYMBOL("mallory"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") } },
{ "blocked", 1, { MAELYS_DATALOG_SYMBOL("mallory") } }
};
static void load_document_policy(void) {
check_status(maelys_datalog_policy_load_inline(domain.name, "document-access", source,
strlen(source), &policy, NULL));
check_status(maelys_datalog_session_create(policy, 0, &session));
}
static void prepare_context(unsigned step) {
(void)facts;
if (step > 1) check_status(maelys_datalog_register_filter_module(&suffix_module));
if (step > 2) check_status(maelys_datalog_register_planner_module(&planner_module));
if (step > 3) check_status(maelys_datalog_domain_register_advanced(&domain,
"Document access with a native file-suffix filter", install_document_predicates));
if (step > 4) load_document_policy();
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
prepare_context(5);
cleanup_context();
return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}modules.c
#include <maelys/datalog.h>
#include <maelys/datalog_builders.h>
#include <maelys/datalog_module.h>
#include <maelys/datalog_program.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_result_t *result = NULL;
static int cleanup_failed = 0;
static void check_status(maelys_datalog_status_t status) {
if (status != MAELYS_DATALOG_STATUS_OK) {
fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status));
exit(EXIT_FAILURE);
}
}
static void cleanup_context(void) {
if (result) { if (maelys_datalog_result_free(result)) cleanup_failed = 1; result = NULL; }
if (session) { if (maelys_datalog_session_free(session)) cleanup_failed = 1; session = NULL; }
if (policy) { if (maelys_datalog_policy_free(policy)) cleanup_failed = 1; policy = NULL; }
}
/* The filter is pure and bounded. No callback keeps pointers or calls the engine. */
static maelys_datalog_status_t validate_suffix(const unsigned char *pattern, size_t length) {
if (!pattern || !length || length > 63) return MAELYS_DATALOG_STATUS_INVALID_FIELD;
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t suffix_cost(size_t value_length, size_t pattern_length, size_t *out_cost) {
(void)value_length;
if (!out_cost) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
if (pattern_length == SIZE_MAX) return MAELYS_DATALOG_STATUS_PAYLOAD_TOO_LARGE;
*out_cost = pattern_length + 1;
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t evaluate_suffix(const unsigned char *value, size_t value_length,
const unsigned char *pattern, size_t pattern_length, int *out_matched) {
if (!value || !pattern || !out_matched) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
*out_matched = value_length >= pattern_length &&
memcmp(value + value_length - pattern_length, pattern, pattern_length) == 0;
return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_filter_module_t suffix_module = {
MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_filter_module_t),
"document_suffix", "example.document-suffix.bytes-v1.cost-pattern-plus-one",
validate_suffix, suffix_cost, evaluate_suffix
};
/* The core supplies only safe choices; this callback never reorders the array. */
static maelys_datalog_status_t choose_join(const maelys_datalog_join_candidate_t *candidates,
size_t candidate_count, size_t *out_candidate_index) {
if (!candidates || !candidate_count || !out_candidate_index)
return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
size_t best = 0;
for (size_t i = 1; i < candidate_count; ++i)
if (candidates[i].default_score > candidates[best].default_score ||
(candidates[i].default_score == candidates[best].default_score &&
candidates[i].body_index < candidates[best].body_index)) best = i;
*out_candidate_index = best;
return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_planner_module_t planner_module = {
MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_planner_module_t),
"document_join", "example.document-join.score-then-body-v1", choose_join
};
static const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2)
};
static maelys_datalog_status_t install_document_predicates(maelys_datalog_domain_builder_t *builder) {
for (size_t i = 0; i < sizeof(predicates) / sizeof(predicates[0]); ++i) {
maelys_datalog_status_t status = maelys_datalog_domain_builder_add(builder, &predicates[i]);
if (status != MAELYS_DATALOG_STATUS_OK) return status;
}
return MAELYS_DATALOG_STATUS_OK;
}
static const char *const atoms[] = { ".pdf" };
static const maelys_datalog_domain_t domain = {
"document_modules", NULL, 0, atoms, sizeof(atoms) / sizeof(atoms[0])
};
static const char source[] =
"allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)), "
"document_suffix(Doc, \".pdf\").\n";
static const maelys_datalog_fact_t facts[] = {
{ "user", 1, { MAELYS_DATALOG_SYMBOL("alice") } },
{ "user", 1, { MAELYS_DATALOG_SYMBOL("mallory") } },
{ "owns", 2, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") } },
{ "owns", 2, { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("draft.txt") } },
{ "owns", 2, { MAELYS_DATALOG_SYMBOL("mallory"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") } },
{ "blocked", 1, { MAELYS_DATALOG_SYMBOL("mallory") } }
};
static void load_document_policy(void) {
check_status(maelys_datalog_policy_load_inline(domain.name, "document-access", source,
strlen(source), &policy, NULL));
check_status(maelys_datalog_session_create(policy, 0, &session));
}
static void prepare_context(unsigned step) {
(void)facts;
if (step > 1) check_status(maelys_datalog_register_filter_module(&suffix_module));
if (step > 2) check_status(maelys_datalog_register_planner_module(&planner_module));
if (step > 3) check_status(maelys_datalog_domain_register_advanced(&domain,
"Document access with a native file-suffix filter", install_document_predicates));
if (step > 4) load_document_policy();
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
prepare_context(1);
/* API_REFERENCE_EXAMPLE */
cleanup_context();
return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}program-variable-names.c
/* Source-name lookup: the second rule contains an anonymous variable. */
#include <maelys/datalog_program.h>
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static const maelys_datalog_program_t *program = NULL;
static void cleanup_context(void) {
if (session != NULL) { cleanup_status(maelys_datalog_session_free(session)); session = NULL; }
if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_POLICY_FACT("user", 1),
MAELYS_DATALOG_IDB_QUERY("allow", 1)
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("program-example", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "user(7). allow(User) :- user(User). allow(9) :- user(_).";
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("program-example", "program-example",
source, strlen(source), &policy, &diagnostic));
check_status(maelys_datalog_session_create(policy, 0, &session));
check_status(maelys_datalog_session_program(session, &program));
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}program.c
/* Program inspection borrows its view from a live session. */
#include <maelys/datalog_program.h>
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static const maelys_datalog_program_t *program = NULL;
static void cleanup_context(void) {
if (session != NULL) { cleanup_status(maelys_datalog_session_free(session)); session = NULL; }
if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_POLICY_FACT("user", 1),
MAELYS_DATALOG_IDB_QUERY("allow", 1)
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("program-example", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "user(7). allow(User) :- user(User).";
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("program-example", "program-example",
source, strlen(source), &policy, &diagnostic));
check_status(maelys_datalog_session_create(policy, 0, &session));
check_status(maelys_datalog_session_program(session, &program));
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}querying.c
/* Page extension: preserves this page’s reviewed document-access scenario. */
static maelys_datalog_result_t *result = NULL;
static maelys_datalog_input_edb_t *edb = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_policy_t *policy = NULL;
static void cleanup_context(void) {
if (result != NULL) {
cleanup_status(maelys_datalog_result_free(result));
result = NULL;
}
if (edb != NULL) {
cleanup_status(maelys_datalog_input_edb_free(edb));
edb = NULL;
}
if (session != NULL) {
cleanup_status(maelys_datalog_session_free(session));
session = NULL;
}
if (policy != NULL) {
cleanup_status(maelys_datalog_policy_free(policy));
policy = NULL;
}
}
/* Page reference context; the document-access case from the guides. */
/* Application-owned setup shared by the reviewed fragments. */
static MAELYS_DATALOG_EXPLANATION_STORAGE(storage, 256u * 1024u);
static const maelys_datalog_value_t terms[] = {
MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf"),
};
static maelys_datalog_status_t prepare(
maelys_datalog_result_t *result, maelys_datalog_prepared_explanation_t **explanation) {
return maelys_datalog_result_prepare_explanation(
result, MAELYS_DATALOG_EXPLAIN_TRUE, "allow", terms, 2u,
storage, sizeof(storage), explanation);
}
static const maelys_datalog_value_t absent_terms[] = {
MAELYS_DATALOG_SYMBOL("mallory"), MAELYS_DATALOG_SYMBOL("roadmap.pdf"),
};
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2),
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "allow(User, Doc) :- owns(User, Doc), not(blocked(User)).";
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("documents", "reference-context", source, strlen(source), &policy, &diagnostic));
check_status(maelys_datalog_session_create(policy, 0u, &session));
check_status(maelys_datalog_input_edb_create(&edb));
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "owns", "alice", "roadmap.pdf"));
/* Intern the absent-query user without granting document ownership. */
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "user", "mallory"));
check_status(maelys_datalog_session_solve_edb(session, edb, &result, &diagnostic));
/* Prepare vocabulary and validate the caller workspace, without acquiring a lease. */
maelys_datalog_fact_view_t fact;
size_t count = 0;
check_status(maelys_datalog_result_enumerate(
result, "allow", 2u, &fact, 1u, &count));
if (count != 1u) return EXIT_FAILURE;
size_t bytes = 0, alignment = 0;
check_status(maelys_datalog_result_explanation_storage_requirements(
result, MAELYS_DATALOG_EXPLAIN_TRUE, &bytes, &alignment));
if (bytes > sizeof(storage) ||
alignment > _Alignof(max_align_t)) return EXIT_FAILURE;
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}registration.c
/* Registration extension of the shared C reference declarations. */
#include <maelys/datalog_extension.h>
#include <maelys/datalog_frontend.h>
#include <maelys/datalog_module.h>
#include <maelys/datalog_backend.h>
#include <stdint.h>
static maelys_datalog_context_t *context = NULL;
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_config_t *config = NULL;
static maelys_datalog_diagnostic_t diagnostic;
static const char policy_source[] =
"allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)).";
static void cleanup_context(void) {
if (config) { cleanup_status(maelys_datalog_session_config_free(config)); config = NULL; }
if (policy) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
if (context) { cleanup_status(maelys_datalog_context_free(context)); context = NULL; }
}
static void *allocate_policy_storage(size_t bytes, size_t alignment) {
if (alignment > _Alignof(max_align_t)) exit(EXIT_FAILURE);
void *arena = malloc(bytes);
if (!arena) exit(EXIT_FAILURE);
return arena;
}
static const char grant_command[] = "grant alice roadmap.pdf";
static const maelys_datalog_ir_atom_t approved_fact = {
.predicate = "approved", .arity = 2,
.terms = {{.kind = MAELYS_DATALOG_IR_SYMBOL, .as.symbol = "alice"},
{.kind = MAELYS_DATALOG_IR_SYMBOL, .as.symbol = "roadmap.pdf"}}
};
static const maelys_datalog_ir_rule_t allow_rule = {
.head = {.predicate = "allow", .arity = 2,
.terms = {{.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 0},
{.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 1}}},
.body_count = 3,
.body = {
{.kind = MAELYS_DATALOG_IR_ATOM, .atom = {.predicate = "approved", .arity = 2,
.terms = {{.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 0},
{.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 1}}}},
{.kind = MAELYS_DATALOG_IR_NEGATION, .atom = {.predicate = "blocked", .arity = 1,
.terms = {{.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 0}}}},
{.kind = MAELYS_DATALOG_IR_FILTER,
.filter_name = "document_suffix",
.filter_semantic_id = "example.document-suffix.bytes-v1.cost-pattern-plus-one",
.pattern = (const unsigned char *)".pdf", .pattern_length = 4,
.filter_value = {.kind = MAELYS_DATALOG_IR_VARIABLE, .as.variable = 1}}
}
};
/* Accept one command and propagate every builder failure. */
static maelys_datalog_status_t lower_grant(const char *text, size_t length,
maelys_datalog_program_builder_t *builder, maelys_datalog_diagnostic_t *diagnostic) {
(void)diagnostic;
if (length != sizeof(grant_command) - 1 || memcmp(text, grant_command, length) != 0)
return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
maelys_datalog_status_t status = maelys_datalog_program_add_fact(builder, &approved_fact);
if (status != MAELYS_DATALOG_STATUS_OK) return status;
return maelys_datalog_program_add_rule(builder, &allow_rule);
}
static const maelys_datalog_frontend_t grant_frontend = {
.abi_version = MAELYS_DATALOG_PROGRAM_ABI_VERSION,
.struct_size = sizeof(grant_frontend),
.name = "grant_command", .semantic_id = "example.grant-command.pdf.v1",
.lower = lower_grant
};
/* A native filter validates its pattern, prices its work, and tests the bytes. */
static maelys_datalog_status_t validate_suffix(const unsigned char *pattern, size_t length) {
if (!pattern || !length || length > 63) return MAELYS_DATALOG_STATUS_INVALID_FIELD;
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t suffix_cost(size_t value_length, size_t pattern_length, size_t *out_cost) {
(void)value_length;
if (!out_cost) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
if (pattern_length == SIZE_MAX) return MAELYS_DATALOG_STATUS_PAYLOAD_TOO_LARGE;
*out_cost = pattern_length + 1;
return MAELYS_DATALOG_STATUS_OK;
}
static maelys_datalog_status_t evaluate_suffix(const unsigned char *value, size_t value_length,
const unsigned char *pattern, size_t pattern_length, int *out_matched) {
if (!value || !pattern || !out_matched) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
*out_matched = value_length >= pattern_length &&
memcmp(value + value_length - pattern_length, pattern, pattern_length) == 0;
return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_filter_module_t suffix_module = {
MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_filter_module_t),
"document_suffix", "example.document-suffix.bytes-v1.cost-pattern-plus-one",
validate_suffix, suffix_cost, evaluate_suffix
};
/* Select only among the safe candidates supplied by the core. */
static maelys_datalog_status_t choose_join(const maelys_datalog_join_candidate_t *candidates,
size_t count, size_t *out_index) {
if (!candidates || !count || !out_index) return MAELYS_DATALOG_STATUS_INVALID_ARGUMENT;
size_t best = 0;
for (size_t i = 1; i < count; ++i)
if (candidates[i].default_score > candidates[best].default_score ||
(candidates[i].default_score == candidates[best].default_score &&
candidates[i].body_index < candidates[best].body_index)) best = i;
*out_index = best;
return MAELYS_DATALOG_STATUS_OK;
}
static const maelys_datalog_planner_module_t document_planner = {
MAELYS_DATALOG_MODULE_ABI_VERSION, sizeof(maelys_datalog_planner_module_t),
"document_join", "example.document-join.score-then-body-v1", choose_join
};
/* This bundle declares components; registering it does not execute callbacks. */
static const maelys_datalog_extension_t document_components = {
.abi_version = MAELYS_DATALOG_EXTENSION_ABI_VERSION,
.struct_size = sizeof(document_components),
.name = "document_components", .semantic_id = "example.document-components.v1",
.frontends = &grant_frontend, .frontend_count = 1,
.filters = &suffix_module, .filter_count = 1,
.planners = &document_planner, .planner_count = 1
};
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_POLICY_FACT("approved", 2),
MAELYS_DATALOG_IDB_QUERY("allow", 2)
};
const char *const atoms[] = {"alice", "roadmap.pdf"};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_WITH_ATOMS("registration_cards", predicates, atoms);
check_status(maelys_datalog_domain_register(&domain));
check_status(maelys_datalog_policy_load_inline("registration_cards", "reference-context",
policy_source, strlen(policy_source), &policy, &diagnostic));
check_status(maelys_datalog_context_create(&context));
check_status(maelys_datalog_session_config_create(&config));
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}registries.c
/* Registries extension of the common C reference declarations. */
static void cleanup_context(void) {}
int main(void) {
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("delegated", 2), MAELYS_DATALOG_EDB("blocked", 1),
MAELYS_DATALOG_IDB("can_read", 2), MAELYS_DATALOG_IDB_QUERY("has_any_document", 1),
MAELYS_DATALOG_IDB_QUERY("allow", 2),
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
{
/* API_REFERENCE_EXAMPLE */
}
return EXIT_SUCCESS;
}rulesets.c
/* Page extension: preserves this page’s reviewed document-access scenario. */
static maelys_datalog_policy_t *policy = NULL;
static void cleanup_context(void) {
if (policy != NULL) {
cleanup_status(maelys_datalog_policy_free(policy));
policy = NULL;
}
}
/* Page reference context; document-access declarations and policy from the guides. */
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2),
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "allow(User, Doc) :- owns(User, Doc), not(blocked(User)).";
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("documents", "documents.main", source, strlen(source), &policy, &diagnostic));
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}session-inputs.c
/* Retained inputs use the same document-access vocabulary as the Solving guide. */
#include <maelys/datalog_inputs.h>
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_session_inputs_t *inputs = NULL;
static maelys_datalog_result_t *result = NULL;
static void *storage = NULL;
static maelys_datalog_input_options_t options = MAELYS_DATALOG_INPUT_OPTIONS_INIT;
static void cleanup_context(void) {
if (result != NULL) { cleanup_status(maelys_datalog_result_free(result)); result = NULL; }
if (inputs != NULL) { cleanup_status(maelys_datalog_session_inputs_free(inputs)); inputs = NULL; }
if (session != NULL) { cleanup_status(maelys_datalog_session_free(session)); session = NULL; }
if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
free(storage);
storage = NULL;
}
static void *allocate_storage(size_t bytes, size_t alignment) {
void *memory = malloc(bytes);
if (memory == NULL || alignment == 0 || (uintptr_t)memory % alignment != 0) {
free(memory);
fputs("Storage allocation failed\n", stderr);
exit(EXIT_FAILURE);
}
return memory;
}
static void create_inputs(void) {
size_t bytes = 0, alignment = 0;
check_status(maelys_datalog_session_inputs_storage_requirements(session, &options, &bytes, &alignment));
storage = allocate_storage(bytes, alignment);
check_status(maelys_datalog_session_inputs_init(session, &options, storage, bytes, &inputs));
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2),
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "allow(User, Doc) :- owns(User, Doc), not(blocked(User)).";
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("documents", "reference-context", source,
strlen(source), &policy, &diagnostic));
check_status(maelys_datalog_session_create(policy, 0u, &session));
const char *symbols[] = {"alice", "roadmap.pdf"};
options.fact_capacity = 2;
options.addition_capacity = 2;
options.removal_capacity = 2;
options.symbols = symbols;
options.symbol_count = sizeof(symbols) / sizeof(symbols[0]);
const maelys_datalog_fact_t facts[] = {
{ .predicate = "owns", .arity = 2u, .terms = {
MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf"),
} },
};
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}session-resources.c
/* Published application resources; the context explicitly selects the installed reference ABI 6 backend. */
#include <maelys/datalog_resources.h>
#include <maelys/datalog_extension.h>
#include <stdint.h>
static maelys_datalog_policy_t *policy = NULL, *caller_policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_session_config_t *config = NULL;
static void *policy_storage = NULL, *session_storage = NULL;
static void cleanup_context(void) {
if (session != NULL) { cleanup_status(maelys_datalog_session_free(session)); session = NULL; }
if (config != NULL) { cleanup_status(maelys_datalog_session_config_free(config)); config = NULL; }
if (caller_policy != NULL) { cleanup_status(maelys_datalog_policy_free(caller_policy)); caller_policy = NULL; }
if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
free(session_storage); session_storage = NULL;
free(policy_storage); policy_storage = NULL;
}
static void *allocate_storage(size_t bytes, size_t alignment) {
void *memory = malloc(bytes);
if (memory == NULL || alignment == 0 || (uintptr_t)memory % alignment != 0) {
free(memory); fputs("Storage allocation failed\n", stderr); exit(EXIT_FAILURE);
}
return memory;
}
static void create_session(void) {
check_status(maelys_datalog_session_create_configured(policy, 0, config, &session));
}
static int allocation_stats_unchanged(
const maelys_datalog_session_allocation_stats_t *a,
const maelys_datalog_session_allocation_stats_t *b) {
return a->struct_size == b->struct_size
&& a->contract_version == b->contract_version
&& a->reserved == b->reserved
&& a->required_features == b->required_features
&& a->cap_bytes == b->cap_bytes
&& a->current_bytes == b->current_bytes
&& a->remaining_bytes == b->remaining_bytes
&& a->operation_peak_bytes == b->operation_peak_bytes;
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2),
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "allow(User, Doc) :- owns(User, Doc), not(blocked(User)).";
const char *manifest_json = "{\"policy_set_id\":\"documents\",\"policy_set_version\":\"1.0.0\",\"manifest_version\":\"1\",\"default_profile\":\"MAELYS-DATALOG-v2\",\"created_for\":\"production\",\"strict_loading\":true,\"fail_closed\":true,\"capabilities\":[],\"policies\":[{\"policy_id\":\"documents.main\",\"domain\":\"documents\",\"file\":\"documents.dl\",\"sha256\":\"c5ec08d836b313af6e49ab7c49e811d84e0e856884fab645282d74682ceac454\",\"mode\":\"enforce\",\"enabled\":true,\"description\":\"Document access\",\"queries\":[{\"name\":\"allow\",\"arity\":2}]}]}";
const maelys_datalog_policy_bundle_entry_t bundle[] = {
{ .policy_id = "documents.main", .src = source, .src_len = strlen(source) },
};
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("documents", "reference-context", source,
strlen(source), &policy, &diagnostic));
check_status(maelys_datalog_session_config_create(&config));
check_status(maelys_datalog_session_config_set_backend_v6(config, maelys_datalog_backend_reference_v6()));
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}solving.c
/* Solving extension of the common C reference declarations. */
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_session_config_t *config = NULL;
static maelys_datalog_input_edb_t *edb = NULL;
static maelys_datalog_result_t *result = NULL;
static void *storage = NULL;
static void cleanup_context(void) {
if (result != NULL) { cleanup_status(maelys_datalog_result_free(result)); result = NULL; }
if (session != NULL) { cleanup_status(maelys_datalog_session_free(session)); session = NULL; }
if (config != NULL) { cleanup_status(maelys_datalog_session_config_free(config)); config = NULL; }
if (edb != NULL) { cleanup_status(maelys_datalog_input_edb_free(edb)); edb = NULL; }
if (policy != NULL) { cleanup_status(maelys_datalog_policy_free(policy)); policy = NULL; }
free(storage);
storage = NULL;
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_IDB_QUERY("allow", 2),
};
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_NO_ATOMS("documents", predicates);
check_status(maelys_datalog_domain_register(&domain));
const char *source = "allow(User, Doc) :- owns(User, Doc), not(blocked(User)).";
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("documents", "reference-context", source,
strlen(source), &policy, &diagnostic));
check_status(maelys_datalog_session_create(policy, 0u, &session));
check_status(maelys_datalog_session_config_create(&config));
check_status(maelys_datalog_input_edb_create(&edb));
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "owns", "alice", "roadmap.pdf"));
const maelys_datalog_fact_t facts[] = {
{ .predicate = "owns", .arity = 2u, .terms = {
MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf"),
} },
};
const size_t fact_count = sizeof(facts) / sizeof(facts[0]);
size_t storage_bytes = 0, storage_alignment = 0;
check_status(maelys_datalog_session_explanation_storage_bound(session,
MAELYS_DATALOG_EXPLAIN_TRUE, &storage_bytes, &storage_alignment));
storage = malloc(storage_bytes);
if (storage == NULL) {
fputs("Explanation workspace allocation failed\n", stderr);
return EXIT_FAILURE;
}
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
if (cleanup_failed) return EXIT_FAILURE;
return EXIT_SUCCESS;
}structured-explanations.c
#include <maelys/datalog.h>
#include <maelys/datalog_builders.h>
#include <maelys/datalog_explanations.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
static maelys_datalog_policy_t *policy = NULL;
static maelys_datalog_session_t *session = NULL;
static maelys_datalog_input_edb_t *edb = NULL;
static maelys_datalog_result_t *result = NULL;
static maelys_datalog_prepared_explanation_t *prepared = NULL;
static void *storage = NULL;
static size_t storage_bytes = 0;
static int cleanup_failed = 0;
static void check_status(maelys_datalog_status_t status) {
if (status != MAELYS_DATALOG_STATUS_OK) {
fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status));
exit(EXIT_FAILURE);
}
}
static void cleanup_context(void) {
if (prepared) { if (maelys_datalog_prepared_explanation_release(prepared)) cleanup_failed = 1; prepared = NULL; }
free(storage); storage = NULL;
if (result) { if (maelys_datalog_result_free(result)) cleanup_failed = 1; result = NULL; }
if (edb) { if (maelys_datalog_input_edb_free(edb)) cleanup_failed = 1; edb = NULL; }
if (session) { if (maelys_datalog_session_free(session)) cleanup_failed = 1; session = NULL; }
if (policy) { if (maelys_datalog_policy_free(policy)) cleanup_failed = 1; policy = NULL; }
}
static const char source[] =
"admin(\"alice\").\n"
"owner_of(User, Doc) :- owns(User, Doc).\n"
"allow(User, Doc) :- owner_of(User, Doc), user(User), not(blocked(User)).\n"
"allow(User, Doc) :- admin(User), user(User), owns(User, Doc).\n";
static const maelys_datalog_value_t alice[] = { MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") };
static const maelys_datalog_value_t mallory[] = { MAELYS_DATALOG_SYMBOL("mallory"), MAELYS_DATALOG_SYMBOL("roadmap.pdf") };
static void print_value(const maelys_datalog_value_t *value) {
switch (value->kind) {
case MAELYS_DATALOG_VALUE_SYMBOL: fputs(value->as.symbol, stdout); break;
case MAELYS_DATALOG_VALUE_INTEGER: printf("%" PRId64, value->as.integer); break;
case MAELYS_DATALOG_VALUE_BOOLEAN: fputs(value->as.boolean ? "true" : "false", stdout); break;
default: fputs("Unexpected value kind\n", stderr); exit(EXIT_FAILURE);
}
}
static void print_fact(const maelys_datalog_fact_t *fact) {
printf("%s(", fact->predicate);
for (size_t i = 0; i < fact->arity; ++i) { if (i) fputs(", ", stdout); print_value(&fact->terms[i]); }
putchar(')');
}
static void print_atom(const maelys_datalog_ir_atom_t *atom) {
printf("%s(", atom->predicate);
for (size_t i = 0; i < atom->arity; ++i) {
if (i) fputs(", ", stdout);
const maelys_datalog_ir_term_t *term = &atom->terms[i];
switch (term->kind) {
case MAELYS_DATALOG_IR_SYMBOL: fputs(term->as.symbol, stdout); break;
case MAELYS_DATALOG_IR_INTEGER: printf("%" PRId64, term->as.integer); break;
case MAELYS_DATALOG_IR_BOOLEAN: fputs(term->as.boolean ? "true" : "false", stdout); break;
case MAELYS_DATALOG_IR_VARIABLE: printf("V%" PRIu32, term->as.variable); break;
default: exit(EXIT_FAILURE);
}
}
putchar(')');
}
static const char *origin_name(unsigned origin) {
switch (origin) {
case MAELYS_DATALOG_EXPLANATION_ORIGIN_POLICY_FACT: return "policy fact";
case MAELYS_DATALOG_EXPLANATION_ORIGIN_EDB: return "input";
case MAELYS_DATALOG_EXPLANATION_ORIGIN_IDB: return "derived";
case MAELYS_DATALOG_EXPLANATION_ORIGIN_NOT_APPLICABLE: return "no source";
default: return "unknown";
}
}
static const char *premise_name(unsigned kind) {
switch (kind) {
case MAELYS_DATALOG_EXPLANATION_PREMISE_POSITIVE_FACT: return "positive fact";
case MAELYS_DATALOG_EXPLANATION_PREMISE_NEGATED_ABSENCE: return "negated absence";
default: return "other premise";
}
}
static const char *obstacle_name(unsigned kind) {
switch (kind) {
case MAELYS_DATALOG_WHY_FALSE_OBSTACLE_POSITIVE_NO_MATCH: return "missing fact";
case MAELYS_DATALOG_WHY_FALSE_OBSTACLE_NEGATIVE_CONTRADICTED: return "negation contradicted";
default: return "other obstacle";
}
}
static void prepare_silently(maelys_datalog_explanation_kind_t kind, const maelys_datalog_value_t *terms) {
check_status(maelys_datalog_result_prepare_explanation(result, kind, "allow", terms, 2,
storage, storage_bytes, &prepared));
}
int main(void) {
if (atexit(cleanup_context) != 0) return EXIT_FAILURE;
const maelys_datalog_predicate_t predicates[] = {
MAELYS_DATALOG_EDB("user", 1), MAELYS_DATALOG_EDB("owns", 2),
MAELYS_DATALOG_EDB("blocked", 1), MAELYS_DATALOG_POLICY_FACT("admin", 1),
MAELYS_DATALOG_IDB("owner_of", 2), MAELYS_DATALOG_IDB_QUERY("allow", 2)
};
const char *const atoms[] = { "alice" };
const maelys_datalog_domain_t domain = MAELYS_DATALOG_DOMAIN_WITH_ATOMS("documents", predicates, atoms);
check_status(maelys_datalog_domain_register(&domain));
maelys_datalog_diagnostic_t diagnostic = MAELYS_DATALOG_DIAGNOSTIC_INIT;
check_status(maelys_datalog_policy_load_inline("documents", "document-access", source, strlen(source), &policy, &diagnostic));
check_status(maelys_datalog_session_create(policy, 0, &session));
check_status(maelys_datalog_input_edb_create(&edb));
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "user", "alice"));
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "user", "mallory"));
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "owns", "alice", "roadmap.pdf"));
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "owns", "mallory", "roadmap.pdf"));
check_status(MAELYS_DATALOG_ADD_FACT(edb, &diagnostic, "blocked", "mallory"));
check_status(maelys_datalog_session_solve_edb(session, edb, &result, &diagnostic));
size_t true_bytes = 0, false_bytes = 0, true_alignment = 0, false_alignment = 0;
check_status(maelys_datalog_result_explanation_storage_requirements(result, MAELYS_DATALOG_EXPLAIN_TRUE, &true_bytes, &true_alignment));
check_status(maelys_datalog_result_explanation_storage_requirements(result, MAELYS_DATALOG_EXPLAIN_FALSE, &false_bytes, &false_alignment));
if (true_alignment > _Alignof(max_align_t) || false_alignment > _Alignof(max_align_t)) return EXIT_FAILURE;
storage_bytes = true_bytes > false_bytes ? true_bytes : false_bytes;
storage = malloc(storage_bytes);
if (!storage) return EXIT_FAILURE;
prepare_silently(MAELYS_DATALOG_EXPLAIN_TRUE, alice);
{
/* API_REFERENCE_EXAMPLE */
}
cleanup_context();
return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}document-access.c
/* Common C reference declarations; concatenated before the page extension. */
#include <maelys/datalog.h>
#include <maelys/datalog_builders.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
/* The page extension owns cleanup; no constructor is hidden in the runner. */
static void cleanup_context(void);
static int cleanup_failed = 0;
static void check_status(maelys_datalog_status_t status) {
if (status != MAELYS_DATALOG_STATUS_OK) {
fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status));
exit(EXIT_FAILURE);
}
}
/* Label each output line without changing the text buffer. */
static void print_text_lines(const char *label, const char *text) {
while (*text != '\0') {
const char *end = strchr(text, '\n');
printf("%s: ", label);
fwrite(text, 1, end ? (size_t)(end - text) : strlen(text), stdout);
putchar('\n');
if (end == NULL) break;
text = end + 1;
}
}
/* Cleanup failures must not recursively invoke check_status. */
static void cleanup_status(maelys_datalog_status_t status) {
if (status != MAELYS_DATALOG_STATUS_OK) {
cleanup_failed = 1;
fprintf(stderr, "Context cleanup failed: %s\n", maelys_datalog_status_name(status));
}
}document-access.ts.txt
// Shared imports, document-access declarations and resource cleanup.
// This file is concatenated before the selected page extension.
import { createHash } from 'node:crypto'
import { Engine, Predicate, SessionCapacities, Capability, ExplanationKind,
MaelysDatalogError, Status, PRED_EDB, PRED_IDB, PRED_QUERY, PRED_POLICY_FACT,
type Fact, type CapacityOptions, type SessionOptions, type EngineOptions,
type ManifestOptions, type ManifestInput, type WasmModule } from '@maelys-dev/datalog/wasm'
const documentDomain = 'documents'
const documentPolicy = 'allow(User, Doc) :- owns(User, Doc), not(blocked(User)).'
// The manifest/ruleset examples use the one-argument policy from their guides.
const userPolicy = 'allow(User) :- user(User).'
function registerDocuments(engine: Engine) {
engine.registerDomain(documentDomain, [
Predicate.edb('user', 1), Predicate.edb('owns', 2), Predicate.edb('blocked', 1),
Predicate.idbQuery('allow', 2),
], [])
}
function registerUsers(engine: Engine) {
engine.registerDomain(documentDomain, [Predicate.edb('user', 1), Predicate.idbQuery('allow', 1)], [])
}
const engines: Engine[] = []
function keepEngine(engine: Engine): Engine {
engines.push(engine)
return engine
}
function closeEngines() {
let failure: unknown
for (const engine of engines.reverse()) {
try { engine.close() } catch (error) { failure ??= error }
}
if (failure) throw failure
}edb.ts.txt
// The try covers setup as well as the displayed example.
try {
// Page reference context; document-access declarations from Full program.
const engine = keepEngine(await Engine.create({ profile: 'small' }))
engine.registerDomain('documents', [
Predicate.edb('user', 1), Predicate.edb('owns', 2), Predicate.edb('blocked', 1),
Predicate.idbQuery('allow', 2),
], [])
const ruleset = engine.loadInlineRuleset('documents', 'reference-context',
'allow(User, Doc) :- owns(User, Doc), not(blocked(User)).')
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}engine.ts.txt
// The try covers setup as well as the displayed example.
try {
// The Engine manifest guide uses the one-argument policy and its exact SHA-256.
const engine = keepEngine(await Engine.create({ profile: 'small' }))
registerUsers(engine)
const policySource = userPolicy + '\n'
const manifestJson = JSON.stringify({
policy_set_id: 'documents', policy_set_version: '1.0.0', manifest_version: '1',
default_profile: 'enforce', created_for: 'production', strict_loading: true,
fail_closed: true, capabilities: [],
policies: [{
policy_id: 'documents.main', domain: 'documents', file: 'documents.dl',
sha256: createHash('sha256').update(policySource).digest('hex'),
mode: 'enforce', enabled: true, description: 'Allow registered users',
queries: [{ name: 'allow', arity: 1 }],
}],
})
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}errors.ts.txt
// The try covers setup as well as the displayed example.
try {
// Page reference context: the first fact nearly fills native text storage.
// The next addFact fits the fact capacity but must raise PAYLOAD_TOO_LARGE
// because its strings exceed the remaining text capacity. The example checks it.
const engine = keepEngine(await Engine.create({ profile: 'small' }))
engine.registerDomain('documents', [
Predicate.edb('user', 1), Predicate.edb('owns', 2), Predicate.edb('blocked', 1),
Predicate.idbQuery('allow', 2),
], [])
const ruleset = engine.loadInlineRuleset('documents', 'reference-context',
'allow(User, Doc) :- owns(User, Doc), not(blocked(User)).')
const input = ruleset.edb({ factCapacity: 2, textCapacity: 12 })
input.addFact('user', ['alice'])
// Reuse the copied engine diagnostic when adding operation context.
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}predicate.ts.txt
// The try covers setup as well as the displayed example.
try {
// Page reference context; declarations are registered explicitly by the displayed examples.
const engine = keepEngine(await Engine.create({ profile: 'small' }))
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}querying.ts.txt
// The try covers setup as well as the displayed example.
try {
// Querying needs an allowed document and an absent user for FALSE explanations.
const engine = keepEngine(await Engine.create({ profile: 'small' }))
registerDocuments(engine)
const ruleset = engine.loadInlineRuleset(documentDomain, 'reference-context', documentPolicy)
const input = ruleset.edb()
input.addFact('user', ['alice'])
input.addFact('user', ['mallory'])
input.addFact('owns', ['alice', 'roadmap.pdf'])
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}rulesets.ts.txt
// The try covers setup as well as the displayed example.
try {
// The Ruleset guide's one-argument policy preserves its compiled-program counts.
const engine = keepEngine(await Engine.create({ profile: 'small' }))
registerUsers(engine)
const source = userPolicy
const ruleset = engine.loadInlineRuleset(documentDomain, 'reference-context', source)
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}session-inputs.ts.txt
import { InputBase, type InputOptions } from '@maelys-dev/datalog/wasm'
// The try covers setup as well as the displayed example.
try {
const engine = keepEngine(await Engine.create({ profile: 'small' }))
registerDocuments(engine)
const ruleset = engine.loadInlineRuleset(documentDomain, 'reference-context', documentPolicy)
const session = ruleset.prepare()
const facts: Fact[] = [
{ predicate: 'user', terms: ['alice'] },
{ predicate: 'owns', terms: ['alice', 'roadmap.pdf'] },
]
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to the session, retained input and live result.
closeEngines()
}solving.ts.txt
// The try covers setup as well as the displayed example.
try {
// Solving uses the same document-access policy with Alice's two input facts.
const engine = keepEngine(await Engine.create({ profile: 'small' }))
registerDocuments(engine)
const ruleset = engine.loadInlineRuleset(documentDomain, 'reference-context', documentPolicy)
const input = ruleset.edb()
input.addFact('user', ['alice'])
input.addFact('owns', ['alice', 'roadmap.pdf'])
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}wasm-integration.ts.txt
// The try covers setup as well as the displayed example.
try {
// Raw-module examples use the verified small-profile asset in the installed release.
const factoryUrl = new URL('./wasm/small/engine.mjs',
import.meta.resolve('@maelys-dev/datalog/package.json'))
const { default: createModule } = await import(factoryUrl.href)
let module!: WasmModule
const engine = keepEngine(await Engine.create({
profile: 'small',
wasmFactory: async options => {
module = await createModule(options)
return module
},
}))
if (!module) throw new Error('The custom factory did not supply a module')
/* API_REFERENCE_EXAMPLE */
} finally {
// Engine.close cascades to every ruleset, input, session and result it owns.
closeEngines()
}