Compiling Context-Switched Preferences into Compact Datalog

People do not hold one fixed ranking over things. A user who wants terse answers while debugging may want long, warm ones when asking for personal advice. A traveller who loved a museum this morning may want a quiet park this afternoon. Systems that answer queries over structured data with user preferences treat those preferences as one global ordering. Systems that personalize language models handle context, but only by searching loosely through raw interaction logs. This proposal joins the two with one idea. Write each preference as a rule guarded by context: "in context C, prefer X over Y, unless a more specific context says otherwise." Then compile all of these rules, once, into a single compact Datalog program, a database query language with reusable named intermediate results. At request time, the current context is supplied as a handful of input facts, so nothing needs to be recompiled or re-derived per situation.

The reason this needs care comes from ontology-mediated query answering. In that field, a user's query is automatically expanded with the background rules of a domain model (an ontology) so that it can run directly on a database. Expansions written as flat unions of simple queries are known to grow exponentially or worse. Context-switched preferences invite the same blowup along a new axis. If $k$ independent context factors can each switch or override preference rules, a flat query that resolves "which ordering is active" can end up enumerating context combinations. The Datalog line of work avoids this kind of growth by sharing structure between branches. We propose to carry that technique over to preferences that change with context. We then test whether the resulting explicit, context-indexed preference store fixes a known failure of language-model personalization: models cannot tell which past sessions are relevant to a new request.

Core Claim

Preferences that depend on context can be expressed as context-guarded, defeasible preference rules over an ontology. They can be compiled into one Datalog program, with stratified negation (negation applied in ordered layers so the result stays well defined) used to encode overrides. That program has three properties. Its size stays polynomial in the number of context factors and rules. It can be evaluated on an existing engine with the current context passed as input facts. It reproduces exactly the skyline and top-k answers that a preference-augmented chase would compute for that context.

The empirical side of the claim is separate and is a hypothesis. Applied to user interaction histories, selecting preferences by explicit context match, rather than by recency or embedding similarity, should recover a large part of the gap between automatic and oracle context retrieval on contextual personalization benchmarks.

Where This Sits

The closest prior work is Preference-Based Query Answering in Datalog+/- Ontologies. It adds user preference rules to Datalog+/-, defines a preference-augmented chase that builds dominance edges between inferred facts, and gives skyline and k-rank semantics. Its complexity results are as follows. Atomic queries are polynomial-time in the size of the data. Conjunctive queries, which join several entities, are $\Sigma^p_2$-complete, a complexity class believed to be harder than NP. Some restricted ontologies admit a translation into first-order logic, and hence plain SQL. Its preferences are global and transitive, and it uses only plain SQL rewriting. We keep its semantics but change two things. Preference edges become conditional on context and can be overridden. The compilation target becomes structure-sharing Datalog. We do not claim to defeat the $\Sigma^p_2$ bound for general conjunctive queries. That result constrains us, so we work in the fragment where it does not bite: atomic and acyclic queries, with the ontology rewritable to Datalog.

The compilation method itself is reused from three systems that keep rewritings compact by sharing structure. Small Datalog Query Rewritings for EL translates the ontology into Datalog once, in linear time, and rewrites the query separately in polynomial time. Practical Datalog Rewriting for Existential Rules (Drewer) compresses rewritings for general existential rules. A Datalog Rewriting Algorithm for Warded Ontologies (WardedRewrite) decomposes query bodies and resolves them in chunks. All three handle monotone rules, where adding facts never removes conclusions. None has a notion of a preference that switches on in one context and is overridden in another. Supplying that is exactly the step we add.

Two strands of evidence motivate the work. First, the expansion literature shows how bad flat rewritings get. They can grow triple-exponentially in Deciding FO-Rewritability in EL. A single covering axiom causes double-exponential growth in A data complexity and rewritability tetrachotomy of ontology-mediated queries with a covering axiom. First-Order Rewritability of Temporal Ontology-Mediated Queries reports exponential growth from temporal dependencies.

Second, the personalization literature shows that context reshapes preferences rather than shifting them. A Situation-aware Enhancer for Personalized Recommendation argues that flat context features only add a bias. SAR-Net uses scenario features to gate history. Ricochet encodes complementarity transitions in an ontology but runs them as in-memory re-ranking over ten users, with no rewriting or complexity analysis. CUPID pins down the failure we target. Language models extract the relevant context factors with under 50% precision and 65% recall, and they improve by 20–30 points when handed only the relevant sessions. Failures are worst on "contrastive" histories, where the relevant constraint appeared long ago.

Language-model personalization methods are also relevant, but they solve a different problem. CIPHER induces text preferences from user edits and retrieves them by cosine similarity. EXACT selects three attributes from a fixed library of 42 and injects them at decoding time. P-Check generates weighted evaluation checklists. All three decide what is relevant by similarity or by a learned model. None of them represents an explicit rule of the form "this preference holds in this context and is overridden in that one."

Research Program

Formal language. The formal part defines a language we call context-guarded PrefDatalog. It has three kinds of rules. Ontology rules are drawn from a fragment rewritable to Datalog, such as EL, DL-Lite, or warded rules. Preference rules have the form $\mathit{Ctx}(c) \wedge \phi(x,y) \rightarrow \mathit{pref}_c(x,y)$, where $\mathit{Ctx}(c)$ is an input fact saying context $c$ is active, $\phi$ is a condition over the data, and $\mathit{pref}_c$ is a candidate preference edge. A specificity order between contexts then determines when one candidate edge defeats a conflicting one. The active preference relation for a given context is the set of candidate edges not defeated by an edge from a strictly more specific active context. Skyline and top-k answers are then computed from that relation as in the original PrefDatalog semantics.

Compilation and size analysis. The compilation proceeds in three steps. First, the ontology is compiled once, using the techniques of Small Datalog Query Rewritings for EL or WardedRewrite. Second, each preference rule becomes one Datalog rule over the input predicate $\mathit{Ctx}$. Third, defeat and dominance become two strata of negation that sit on top. Structure is shared because defeat is computed once per pair of conflicting rules, not once per combination of contexts. The size claim we aim to prove is

$$|\Pi| = O\big(|\Pi_{\mathcal{T}}| + |R| + |D|\big) \quad \text{versus} \quad |\mathrm{UCQ}_{\text{flat}}| = \Omega\big(2^{k}\big)\ \text{for some families}.$$

Here $\Pi$ is our compiled program and $\Pi_{\mathcal{T}}$ is the compiled ontology. $R$ is the set of preference rules, $D$ is the set of defeat pairs between rules, and $k$ is the number of interacting context factors. The second expression is the size of a flat rewriting that resolves the active ordering inline. We expect the lower bound to come from override chains, where whether a rule survives depends on which subset of more specific contexts is active, much as covering axioms force case splits in the tetrachotomy results.

There is an honest open question here. A first-order rewriting that allows nested negation might also stay small. Settling whether it does is part of the theory work, and if it does, our claim narrows to "Datalog is as good as negated SQL, and engines run it better." We will prove correctness against a context-parameterized preference-augmented chase, and we will state data complexity for atomic and acyclic queries.

System. The system part implements the compiler on top of an existing Datalog rewriter. Programs are evaluated on DLV and InteGraal, which A Datalog Rewriting Algorithm for Warded Ontologies found to benefit most from compact rewritings, and on a relational database through SQL with recursion.

Language-model bridge. For each persona in CUPID, a language model turns each past session into explicit facts: the context factors present, and preference statements guarded by those factors. A small hand-written ontology over the context factors supplies specificity. For instance, "grant writing for NIH" is a kind of "formal writing," which is a kind of "writing." At request time, the model extracts the context factors of the new request and asserts them as $\mathit{Ctx}$ facts. The compiled program then returns the active, non-overridden preferences, and these are injected into generation the way EXACT injects attributes. The rule store is consulted by context match, not by position in the log. Recency bias therefore cannot hide a contrastive constraint unless the extraction step itself misses it.

Baselines

The naive reference point for the database side is the flat expansion. It specializes the preference query into one first-order query per reachable context combination, joined by union, and runs on the same relational database. It shows the blowup we claim to avoid, measured as rewriting size, rewriting time, and evaluation time as $k$ grows.

The strongest existing method for the same semantics is the context-parameterized preference-augmented chase of Preference-Based Query Answering in Datalog+/- Ontologies. It is re-run per request with the current context facts added, and implemented on the same engine so that only the strategy differs. We also run a version of WardedRewrite in which context atoms are treated as ordinary input facts and overrides are approximated by resolving them before compilation. Every method gets the same data, the same engines, the same hardware, and a fixed per-query time limit.

No reported result was found on Lacuna for context-guarded or context-overridable preference queries. The nearest reference numbers are from IWARDED: evaluating the Datalog rewriting on DLV, DLV-E, and InteGraal was "up to 50% improvement" over answering the original query directly (A Datalog Rewriting Algorithm for Warded Ontologies). On LUBM∃, summary-based pruning gave up to three orders of magnitude on flat unions (Query Optimization for Ontology-Mediated Query Answering). Because that pruning is an optimizer that composes with any rewriting, we apply it to both the flat expansion and our program rather than treating it as a competitor. Beating the competition means two things. Program size must stay roughly flat in $k$ while the flat expansion grows exponentially. Per-request latency must beat the re-run chase once data reaches the millions of facts, with identical answers in every case.

On CUPID, the strongest reported number is Claude 3.7 Sonnet's inference F1 of 55.8%, from CUPID. We compare against five systems on that benchmark: full-history prompting, CIPHER-style cosine retrieval of induced preferences (Aligning LLM Agents by Learning Latent Preference from User Edits), EXACT attribute injection (EXACT), the released PrefMatcher-7B, and the oracle that receives only the relevant sessions. All use the same backbone model and the same token budget. The bar for success is beating 55.8% F1 with an open backbone, and closing at least half of the gap to the oracle on the contrastive split.

The ablation that isolates our key ingredient keeps the extracted context tags but removes both the override strata and the context ontology. It selects every past preference whose tags intersect the current context. If this ablation matches the full system, then the structure we propose is doing no work on CUPID.

Why not just…?

Why not just put context into the database as facts and use an existing Datalog rewriter? For preferences that only switch on and never override one another, this is exactly right, and our compiler should reduce to it. The existing rewriters (Drewer, WardedRewrite, the EL two-step method) handle monotone rules only. "Prefer X unless a more specific active context prefers Y" needs negation, and no rewriter in the file supports it. If benchmark preferences turn out to rarely conflict, this alternative wins. The share of defeat pairs per CUPID persona, measured after extraction, is the first number we will report. On synthetic workloads, we will vary the override density from zero upward and locate the point where the monotone approach stops returning correct answers.

Why not just rerun the preference chase for the current context on every request? This is a real threat for small per-user stores. A CUPID persona's history is tiny, and chasing it per request is cheap. Our case rests on shared, large stores, such as preferences over a product or place catalogue in the tens of millions of facts. There, the materialization arguments of Conjunctive Query Answering in EL using a Database System and the measured speedups on IWARDED apply. We will report the crossover in data size rather than claim universal dominance. If no crossover appears below 150 million facts on LUBM∃, which is the largest scale in the file, the systems claim fails.

Why not just have a language model tag sessions with context labels and filter, or use embedding retrieval? Embedding retrieval is the mechanism behind CIPHER, and CUPID's 20–30 point oracle gap suggests that similarity does not capture relevance. Tag-and-filter is stronger, and it is essentially our ablation without overrides or hierarchy. If it matches the full system, the honest conclusion is that on CUPID's scale the benefit comes from explicit extraction, not from compilation. We would then present the formal work as a scaling result and drop the accuracy claim.

Proposed Experiments

Size and speed on synthetic preferences. We extend LUBM∃₂₀ (449 rules, 1 to 150 million facts) and the IWARDED generator with synthetic context-guarded preference rules. Three parameters are controlled: the number of context factors (from 2 to 20), the depth of override chains, and the override density. We then measure four quantities: rewriting size, rewriting time, evaluation time on DLV, InteGraal, and a relational database, and exact agreement with the per-context chase.

The first decisive check is the shape of program size as $k$ grows. Our program should grow linearly. The flat expansion should grow exponentially once override chains have depth two or more. If a first-order rewriting with negation also stays polynomial, we will say so and recast the contribution as an engine-level comparison.

Contextual personalization on CUPID. We report inference precision, recall, and F1, and response quality, broken down by the consistent, contrastive, and changing splits, against the baselines above. The second decisive check is the contrastive split. If explicit context selection closes the gap there while full-history prompting does not, recency bias is confirmed as the failure mode and context-indexed retrieval as the fix.

Transfer to subjective preferences. A smaller transfer test runs the same pipeline on PRISM's personalized split, against EXACT's reported preference-modeling accuracy of about 66% and P-Check's 63.62%. Its purpose is to see whether override semantics help when context factors are noisy and subjective. We expect a weaker result there, and it would mark the limit of what explicit rules buy.