C Extension API

Backends guide

Write and execute native backend callbacks for document-access decisions.

Implement a bounded solver for a document-access policy, then select it through three independent backend contracts. The example uses snapshots with ABI 5, a session-bound allocation service with ABI 6, and retained-input transactions with ABI 7; it is a teaching backend for the single normalized rule below, not a general Datalog solver. See the Backends reference for the descriptors, callbacks and borrowed-view contracts.

Document-access policy

This backend accepts only the normalized rule below, sixteen input facts at most, and short symbol values. It is a bounded teaching implementation, not a general-purpose solver; any other program is rejected explicitly.

DATALOG
allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)), ends_with(Doc, ".pdf").

1. Reject programs this backend does not implement

Accept exactly this normalized rule, including its predicate roles, filter identity and variable bindings; refuse every other program shape. In this checked rule the compiled variables 0 and 1 bind User and Doc. The setup loads the policy above and creates a session with the default backend. session_program() obtains that session's compiled program for this first check; creating a session with our backend runs the same guard again through storage_requirements.

Example
CODE
/* 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, filter_calls, emitted;
    int abandon_next;
} 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) {
    size_t bytes, alignment;
    check_status(accept_document_program(witness_program));
    check_status(maelys_datalog_backend_storage_requirements(policy, 0, &documents_v5, &bytes, &alignment));
    report("accepted rule: %s\n", policy_source);
    report("program shape: ok\n");
    const char extra_rule[] = "allow(User, Doc) :- owns(User, Doc), blocked(User).";
    char changed_source[sizeof(policy_source) + sizeof(extra_rule) + 1];
    snprintf(changed_source, sizeof(changed_source), "%s\n%s", policy_source, extra_rule);
    maelys_datalog_policy_t *changed = NULL;
    check_status(maelys_datalog_policy_load_inline("backend_documents", "unsupported-shape",
        changed_source, strlen(changed_source), &changed, &diagnostic));
    maelys_datalog_status_t status = maelys_datalog_backend_storage_requirements(
        changed, 0, &documents_v5, &bytes, &alignment);
    report("extra rule: %s\n", extra_rule);
    report("program shape with the extra rule: %s\n", maelys_datalog_status_name(status));
    if (status != MAELYS_DATALOG_STATUS_UNSUPPORTED) exit(EXIT_FAILURE);
    check_status(maelys_datalog_policy_free(changed));
}
accepted rule: allow(User, Doc) :- user(User), owns(User, Doc), not(blocked(User)), ends_with(Doc, ".pdf").
program shape: ok
extra rule: allow(User, Doc) :- owns(User, Doc), blocked(User).
program shape with the extra rule: unsupported

2. Charge work and emit the complete answer

Own every retained string, charge before bounded work, invoke the selected filter through the host, and emit the entire allow relation. These callbacks advertise positive rules, negation, filters and cooperative work accounting, without explanation support. The core copies and validates emitted facts; an error must propagate instead of publishing a partial answer. Finally, solve once with these callbacks and query the result; the output reports the emitted allow facts and measured filter calls.

Example
CODE
/* 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(document_backend_state *state, const document_set *set,
    maelys_datalog_backend_output_t *output) {
    state->filter_calls = 0; state->emitted = 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;
        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;
        ++state->filter_calls;
        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);
        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])}};
            status = maelys_datalog_backend_emit(output, &answer); if (status) return status;
            ++state->emitted;
        }
    }
    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;
    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, 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 solve_snapshot_once(void) {
    maelys_datalog_session_config_t *snapshot_config = NULL;
    maelys_datalog_session_t *snapshot = NULL;
    check_status(maelys_datalog_session_config_create(&snapshot_config));
    check_status(maelys_datalog_session_config_set_backend(snapshot_config, &documents_v5));
    size_t bytes, alignment;
    check_status(maelys_datalog_backend_storage_requirements(policy, 0, &documents_v5, &bytes, &alignment));
    void *arena = aligned_storage(bytes, alignment);
    const maelys_datalog_backend_storage_t storage = {sizeof(storage), arena, bytes, alignment};
    check_status(maelys_datalog_session_config_set_backend_storage(snapshot_config, &storage));
    check_status(maelys_datalog_session_create_configured(policy, 0, snapshot_config, &snapshot));
    check_status(maelys_datalog_session_solve(snapshot, initial_inputs, 2, &result, &diagnostic));
    maelys_datalog_fact_view_t answers[BACKEND_FACT_LIMIT];
    size_t count, derived;
    check_status(maelys_datalog_result_enumerate(result, "allow", 2, answers, BACKEND_FACT_LIMIT, &count));
    check_status(maelys_datalog_result_derived_fact_count(result, &derived));
    const document_backend_state *state = arena;
    report("allow facts in the result: %zu\n", count);
    report("registered filter calls: %zu\n", state->filter_calls);
    if (count != derived || count != state->emitted || !count || !state->filter_calls) exit(EXIT_FAILURE);
    print_decision("snapshot query, alice");
    release_result();
    check_status(maelys_datalog_session_free(snapshot));
    check_status(maelys_datalog_session_config_free(snapshot_config)); free(arena);
}
allow facts in the result: 1
registered filter calls: 1
snapshot query, alice: allowed

3. Register and select an ABI 5 snapshot backend

Describe ABI 5 with its own type, put it in a native bundle, register and seal the catalog, then explicitly select its name. Supply the provider's measured caller-owned storage before creating the session. Solve a complete input snapshot and query the copied result.

Example
CODE
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;
}
ABI 5 snapshot, alice: allowed

4. Use normalized resources and the ABI 6 host service

ABI 6 adds normalized session resources to requirements and prepare; its snapshot callback retains the ABI 5 solve contract. Opt in to the caller allocator through the extended resource request. Requirements never uses allocation; prepare receives the session-bound host service, inspects a workspace request, then acquires it through that service. The host service is not the raw caller allocator. This example selects documents_v6 directly. For named registration, declare it in extension_v2_t, register the bundle with context_register_v2(), and select its name with session_config_set_context_backend_v6().

Example
CODE
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;
}
ABI 6 host allocation service inspected: yes
workspace fits the session budget: yes
ABI 6 snapshot, alice: allowed

5. Stage ABI 7 inputs without changing committed state

ABI 7 has a different solve callback: REPLACE carries a complete input set, while DELTA removes then adds facts. Copy the callback-scoped views, verify the committed base, and stage the candidate separately. Only commit publishes its facts and adopts next; releasing an uncommitted result means abort. The demonstration sets a backend-local flag to return invalid_state after staging a candidate, so the SDK releases it without calling commit. Its output measures the candidate and confirms that committed facts, commit count and base are unchanged, then queries the result after retrying from that base.

Example
CODE
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;
        status = maelys_datalog_backend_input_at(view, i, &borrowed); 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. */
    maelys_datalog_status_t emitted = emit_document_answers(state, candidate, output);
    if (emitted) return emitted;
    /* The guide explicitly exercises rejection after staging, before host commit. */
    if (state->abandon_next) { state->abandon_next = 0; return MAELYS_DATALOG_STATUS_INVALID_STATE; }
    return MAELYS_DATALOG_STATUS_OK;
}
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 abandon_staged_candidate(void) {
    maelys_datalog_session_config_t *transaction_config = NULL;
    maelys_datalog_session_t *transaction_session = NULL;
    maelys_datalog_session_inputs_t *inputs = NULL;
    check_status(maelys_datalog_session_config_create(&transaction_config));
    check_status(maelys_datalog_session_config_set_backend_v7(transaction_config, &documents_v7));
    void *arena = aligned_storage(sizeof(document_backend_state), _Alignof(document_backend_state));
    const maelys_datalog_backend_storage_t storage = {sizeof(storage), arena,
        sizeof(document_backend_state), _Alignof(document_backend_state)};
    check_status(maelys_datalog_session_config_set_backend_storage(transaction_config, &storage));
    maelys_datalog_session_resource_request_t resources = MAELYS_DATALOG_RESOURCE_REQUEST_INIT;
    resources.capacity_mask = MAELYS_DATALOG_CAPACITY_INPUT_FACTS | MAELYS_DATALOG_CAPACITY_DERIVED_FACTS;
    resources.input_facts = BACKEND_FACT_LIMIT; resources.derived_facts = BACKEND_FACT_LIMIT;
    check_status(maelys_datalog_session_config_set_resources(transaction_config, &resources));
    check_status(maelys_datalog_session_create_configured(policy, 0, transaction_config, &transaction_session));
    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 = 1; options.removal_capacity = 1;
    options.symbols = symbols; options.symbol_count = 2;
    size_t bytes, alignment;
    check_status(maelys_datalog_session_inputs_storage_requirements(transaction_session, &options, &bytes, &alignment));
    void *input_arena = aligned_storage(bytes, alignment);
    check_status(maelys_datalog_session_inputs_init(transaction_session, &options, input_arena, bytes, &inputs));
    maelys_datalog_input_base_t before, after;
    check_status(maelys_datalog_session_inputs_base(inputs, &before));
    check_status(maelys_datalog_session_inputs_replace(inputs, before, initial_inputs, 2, &result, &diagnostic));
    release_result();
    check_status(maelys_datalog_session_inputs_base(inputs, &before));
    document_backend_state *state = arena;
    const document_set committed = state->committed;
    const size_t commits = state->commits, aborts = state->aborts;
    state->abandon_next = 1; /* Ask the backend to reject this fully staged candidate. */
    maelys_datalog_status_t status = maelys_datalog_session_inputs_apply(
        inputs, before, &blocked_alice, 1, NULL, 0, &result, &diagnostic);
    report("candidate facts prepared before rejection: %zu\n", state->candidate.facts.count);
    report("controlled candidate rejection: %s\n", maelys_datalog_status_name(status));
    if (status != MAELYS_DATALOG_STATUS_INVALID_STATE || result) exit(EXIT_FAILURE);
    check_status(maelys_datalog_session_inputs_base(inputs, &after));
    int intact = same_base(before, after) && same_base(before, state->base) &&
        committed.count == state->committed.count && state->commits == commits && state->aborts == aborts + 1;
    for (size_t i = 0; intact && i < committed.count; ++i)
        intact = same_fact(&committed.rows[i], &state->committed.rows[i]);
    report("abandoned candidate left committed facts and base intact: %s\n", intact ? "yes" : "no");
    if (!intact || state->candidate.facts.count != committed.count + 1) exit(EXIT_FAILURE);
    check_status(maelys_datalog_session_inputs_apply(inputs, before, NULL, 0, NULL, 0, &result, &diagnostic));
    print_decision("query after the abandoned candidate, alice"); release_result();
    check_status(maelys_datalog_session_inputs_free(inputs));
    check_status(maelys_datalog_session_free(transaction_session));
    check_status(maelys_datalog_session_config_free(transaction_config)); free(input_arena); free(arena);
}
candidate facts prepared before rejection: 3
controlled candidate rejection: invalid_state
abandoned candidate left committed facts and base intact: yes
query after the abandoned candidate, alice: allowed

6. Replace inputs, then apply a blocking delta

The extension registry accepts ABI 5 and ABI 6 backends; an ABI 7 descriptor is selected directly on the session configuration. Attach a fixed vocabulary before the first solve, replace it with the initial facts, then add blocked(alice). The first result allows Alice; the delta denies her. Compare bases as opaque tokens, never as printed internal identifiers.

Example
CODE
static void run_retained_inputs(void) {
    check_status(maelys_datalog_session_config_create(&config));
    /* The registry accepts ABI 5 and ABI 6; select ABI 7 directly in session configuration. */
    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", "bob", "roadmap.pdf", "notes.txt", "plan.pdf"};
    options.fact_capacity = BACKEND_FACT_LIMIT; options.addition_capacity = 4; options.removal_capacity = 4;
    options.symbols = symbols; options.symbol_count = 5;
    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;
}
ABI 7 replace, alice: allowed
ABI 7 delta after blocking alice: denied
host and backend committed bases agree: yes

7. Reject failed work and release the owners

A transaction that exceeds the configured work budget returns payload_too_large, returns no result and changes neither committed facts nor base. Retry from the unchanged base to verify the previous denial. Ordinary snapshot solving is unavailable while retained inputs are attached, and allocation requests are balanced when the owners are released.

Example
CODE
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("bob")}},
        {"owns", 2, {MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("notes.txt")}},
        {"owns", 2, {MAELYS_DATALOG_SYMBOL("bob"), MAELYS_DATALOG_SYMBOL("plan.pdf")}},
        {"owns", 2, {MAELYS_DATALOG_SYMBOL("bob"), MAELYS_DATALOG_SYMBOL("notes.txt")}}
    };
    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();
    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");
}
over-budget transaction: payload_too_large
failed candidate left committed facts and base intact: yes
retry from the unchanged base, alice: denied
ordinary snapshot while retained inputs are attached: invalid_state
caller allocation requests released: yes
released: results, retained inputs, sessions, policies and context

This example stores at most sixteen input facts with one or two symbol terms of at most sixty-three bytes; larger or differently typed inputs are refused, never truncated. Callbacks are trusted native code, not a sandbox. The resource service and provider storage remain valid through destroy; input views are borrowed only during solve. Results must be released before another solve or session destruction, and backend callback code must stay loaded while the session exists.

Reference context

Insert the seven numbered fragments at API_REFERENCE_EXAMPLE, in order. The context supplies the domain, policy, shared checks and cleanup; the backend callbacks, descriptors, registration and selection remain visible in the steps. Each isolated step executes with its prerequisite state prepared by its context.

CODE
#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;
}
static const maelys_datalog_backend_t documents_v5;
/* API_REFERENCE_EXAMPLE */
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();
    check_supported_program();
    solve_snapshot_once();
    register_and_run_snapshot();
    run_with_resources();
    abandon_staged_candidate();
    run_retained_inputs();
    check_limits_and_release();
    cleanup();
    return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
Full program
CODE
#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;
}
static const maelys_datalog_backend_t documents_v5;
/* 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, filter_calls, emitted;
    int abandon_next;
} 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) {
    size_t bytes, alignment;
    check_status(accept_document_program(witness_program));
    check_status(maelys_datalog_backend_storage_requirements(policy, 0, &documents_v5, &bytes, &alignment));
    report("accepted rule: %s\n", policy_source);
    report("program shape: ok\n");
    const char extra_rule[] = "allow(User, Doc) :- owns(User, Doc), blocked(User).";
    char changed_source[sizeof(policy_source) + sizeof(extra_rule) + 1];
    snprintf(changed_source, sizeof(changed_source), "%s\n%s", policy_source, extra_rule);
    maelys_datalog_policy_t *changed = NULL;
    check_status(maelys_datalog_policy_load_inline("backend_documents", "unsupported-shape",
        changed_source, strlen(changed_source), &changed, &diagnostic));
    maelys_datalog_status_t status = maelys_datalog_backend_storage_requirements(
        changed, 0, &documents_v5, &bytes, &alignment);
    report("extra rule: %s\n", extra_rule);
    report("program shape with the extra rule: %s\n", maelys_datalog_status_name(status));
    if (status != MAELYS_DATALOG_STATUS_UNSUPPORTED) exit(EXIT_FAILURE);
    check_status(maelys_datalog_policy_free(changed));
}
/* 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(document_backend_state *state, const document_set *set,
    maelys_datalog_backend_output_t *output) {
    state->filter_calls = 0; state->emitted = 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;
        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;
        ++state->filter_calls;
        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);
        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])}};
            status = maelys_datalog_backend_emit(output, &answer); if (status) return status;
            ++state->emitted;
        }
    }
    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;
    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, 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 solve_snapshot_once(void) {
    maelys_datalog_session_config_t *snapshot_config = NULL;
    maelys_datalog_session_t *snapshot = NULL;
    check_status(maelys_datalog_session_config_create(&snapshot_config));
    check_status(maelys_datalog_session_config_set_backend(snapshot_config, &documents_v5));
    size_t bytes, alignment;
    check_status(maelys_datalog_backend_storage_requirements(policy, 0, &documents_v5, &bytes, &alignment));
    void *arena = aligned_storage(bytes, alignment);
    const maelys_datalog_backend_storage_t storage = {sizeof(storage), arena, bytes, alignment};
    check_status(maelys_datalog_session_config_set_backend_storage(snapshot_config, &storage));
    check_status(maelys_datalog_session_create_configured(policy, 0, snapshot_config, &snapshot));
    check_status(maelys_datalog_session_solve(snapshot, initial_inputs, 2, &result, &diagnostic));
    maelys_datalog_fact_view_t answers[BACKEND_FACT_LIMIT];
    size_t count, derived;
    check_status(maelys_datalog_result_enumerate(result, "allow", 2, answers, BACKEND_FACT_LIMIT, &count));
    check_status(maelys_datalog_result_derived_fact_count(result, &derived));
    const document_backend_state *state = arena;
    report("allow facts in the result: %zu\n", count);
    report("registered filter calls: %zu\n", state->filter_calls);
    if (count != derived || count != state->emitted || !count || !state->filter_calls) exit(EXIT_FAILURE);
    print_decision("snapshot query, alice");
    release_result();
    check_status(maelys_datalog_session_free(snapshot));
    check_status(maelys_datalog_session_config_free(snapshot_config)); free(arena);
}
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;
        status = maelys_datalog_backend_input_at(view, i, &borrowed); 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. */
    maelys_datalog_status_t emitted = emit_document_answers(state, candidate, output);
    if (emitted) return emitted;
    /* The guide explicitly exercises rejection after staging, before host commit. */
    if (state->abandon_next) { state->abandon_next = 0; return MAELYS_DATALOG_STATUS_INVALID_STATE; }
    return MAELYS_DATALOG_STATUS_OK;
}
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 abandon_staged_candidate(void) {
    maelys_datalog_session_config_t *transaction_config = NULL;
    maelys_datalog_session_t *transaction_session = NULL;
    maelys_datalog_session_inputs_t *inputs = NULL;
    check_status(maelys_datalog_session_config_create(&transaction_config));
    check_status(maelys_datalog_session_config_set_backend_v7(transaction_config, &documents_v7));
    void *arena = aligned_storage(sizeof(document_backend_state), _Alignof(document_backend_state));
    const maelys_datalog_backend_storage_t storage = {sizeof(storage), arena,
        sizeof(document_backend_state), _Alignof(document_backend_state)};
    check_status(maelys_datalog_session_config_set_backend_storage(transaction_config, &storage));
    maelys_datalog_session_resource_request_t resources = MAELYS_DATALOG_RESOURCE_REQUEST_INIT;
    resources.capacity_mask = MAELYS_DATALOG_CAPACITY_INPUT_FACTS | MAELYS_DATALOG_CAPACITY_DERIVED_FACTS;
    resources.input_facts = BACKEND_FACT_LIMIT; resources.derived_facts = BACKEND_FACT_LIMIT;
    check_status(maelys_datalog_session_config_set_resources(transaction_config, &resources));
    check_status(maelys_datalog_session_create_configured(policy, 0, transaction_config, &transaction_session));
    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 = 1; options.removal_capacity = 1;
    options.symbols = symbols; options.symbol_count = 2;
    size_t bytes, alignment;
    check_status(maelys_datalog_session_inputs_storage_requirements(transaction_session, &options, &bytes, &alignment));
    void *input_arena = aligned_storage(bytes, alignment);
    check_status(maelys_datalog_session_inputs_init(transaction_session, &options, input_arena, bytes, &inputs));
    maelys_datalog_input_base_t before, after;
    check_status(maelys_datalog_session_inputs_base(inputs, &before));
    check_status(maelys_datalog_session_inputs_replace(inputs, before, initial_inputs, 2, &result, &diagnostic));
    release_result();
    check_status(maelys_datalog_session_inputs_base(inputs, &before));
    document_backend_state *state = arena;
    const document_set committed = state->committed;
    const size_t commits = state->commits, aborts = state->aborts;
    state->abandon_next = 1; /* Ask the backend to reject this fully staged candidate. */
    maelys_datalog_status_t status = maelys_datalog_session_inputs_apply(
        inputs, before, &blocked_alice, 1, NULL, 0, &result, &diagnostic);
    report("candidate facts prepared before rejection: %zu\n", state->candidate.facts.count);
    report("controlled candidate rejection: %s\n", maelys_datalog_status_name(status));
    if (status != MAELYS_DATALOG_STATUS_INVALID_STATE || result) exit(EXIT_FAILURE);
    check_status(maelys_datalog_session_inputs_base(inputs, &after));
    int intact = same_base(before, after) && same_base(before, state->base) &&
        committed.count == state->committed.count && state->commits == commits && state->aborts == aborts + 1;
    for (size_t i = 0; intact && i < committed.count; ++i)
        intact = same_fact(&committed.rows[i], &state->committed.rows[i]);
    report("abandoned candidate left committed facts and base intact: %s\n", intact ? "yes" : "no");
    if (!intact || state->candidate.facts.count != committed.count + 1) exit(EXIT_FAILURE);
    check_status(maelys_datalog_session_inputs_apply(inputs, before, NULL, 0, NULL, 0, &result, &diagnostic));
    print_decision("query after the abandoned candidate, alice"); release_result();
    check_status(maelys_datalog_session_inputs_free(inputs));
    check_status(maelys_datalog_session_free(transaction_session));
    check_status(maelys_datalog_session_config_free(transaction_config)); free(input_arena); free(arena);
}
static void run_retained_inputs(void) {
    check_status(maelys_datalog_session_config_create(&config));
    /* The registry accepts ABI 5 and ABI 6; select ABI 7 directly in session configuration. */
    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", "bob", "roadmap.pdf", "notes.txt", "plan.pdf"};
    options.fact_capacity = BACKEND_FACT_LIMIT; options.addition_capacity = 4; options.removal_capacity = 4;
    options.symbols = symbols; options.symbol_count = 5;
    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("bob")}},
        {"owns", 2, {MAELYS_DATALOG_SYMBOL("alice"), MAELYS_DATALOG_SYMBOL("notes.txt")}},
        {"owns", 2, {MAELYS_DATALOG_SYMBOL("bob"), MAELYS_DATALOG_SYMBOL("plan.pdf")}},
        {"owns", 2, {MAELYS_DATALOG_SYMBOL("bob"), MAELYS_DATALOG_SYMBOL("notes.txt")}}
    };
    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();
    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();
    check_supported_program();
    solve_snapshot_once();
    register_and_run_snapshot();
    run_with_resources();
    abandon_staged_candidate();
    run_retained_inputs();
    check_limits_and_release();
    cleanup();
    return cleanup_failed ? EXIT_FAILURE : EXIT_SUCCESS;
}