Worked example: Boolean conjunctive queries – evaluation and containment #
This file is a tutorial: it walks, step by step, through the addition of a new problem domain to the library, with NP-completeness proofs at the end. It is meant to be read top to bottom, and to serve as a template for formalizing further problems. The domain is database theory: Boolean conjunctive queries (BCQs) over relational databases with set semantics, and the two classical decision problems about them, both NP-complete by the results of Chandra and Merlin (1977):
- evaluation (combined complexity): given a query
qand a databaseD, doesqhold inD? - containment: given queries
q₁andq₂, is every database satisfyingq₁also a model ofq₂?
To keep the tutorial focused we fix the schema to a single binary relation
E – graph databases. This loses no complexity-theoretic generality (both
problems are already NP-hard for this schema) and everything below extends
mechanically to any fixed relational schema. A BCQ is then an expression
∃ x₁ … xₖ, E(t₁, t₁') ∧ … ∧ E(tₘ, tₘ') where each term tᵢ is a variable
or a constant.
The recipe, common to every problem in the library:
- Vocabulary: a relational
FirstOrder.Languagewhose finite structures are the problem instances. - Semantics: a
Prop-valued predicate on structures of that vocabulary, total on all structures (also the meaningless “junk” ones), with the convention for junk made explicit. - Invariance: the predicate is isomorphism-invariant, giving a bundled
DecisionProblem. - Membership: the problem is in NP, either by exhibiting a
Σ₁second-order definition (SigmaSODefinable) or by an FO reduction to a problem already in NP. - Hardness: an FO reduction from an NP-hard problem of the catalog.
- Completeness: combine 4 and 5.
This tutorial wraps that recipe in the full user-facing arc, which is how
the steps below are numbered: start from the concrete problem in the user's
own formalism (step 1), construct the encoding with the machinery of
DescriptiveComplexity.Encoding – size bounds discharged at construction
(step 3) – prove the encoded problem equivalent to the concrete one (step
6), and only then establish the NP-completeness of the encoded variant,
which faithfulness reads back to the concrete data. The two encoding
obligations – semantic equivalence and size-faithfulness – are both
machine-checked, and they are arguably the steps a library user should worry
about most.
Evaluation goes through this arc directly (steps 1–9); containment reuses
evaluation on both sides – its membership is an FO reduction to evaluation
and its hardness an FO reduction from evaluation – with the classical
Chandra–Merlin homomorphism theorem (DescriptiveComplexity.queryContained_iff_hom)
as the bridge. The reductions are all order-free and quantifier-free.
Main results:
DescriptiveComplexity.CQEval,DescriptiveComplexity.CQContainment: the two bundled decision problems;DescriptiveComplexity.queryContained_iff_hom: the Chandra–Merlin theorem – containment holds iff there is a homomorphism from the right query to the canonical database of the left one;DescriptiveComplexity.concreteQueryHolds_iff_queryHolds: semantic faithfulness of the encoding – on instances built (byDescriptiveComplexity.queryDbStructure) from a concrete query (a list of atoms) and a concrete database (a list of facts), the abstract semantics agrees with the textbook one;DescriptiveComplexity.cqEncodingwithDescriptiveComplexity.cqEncoding_faithful: the bundled encoding – size bounds discharged by construction, semantics faithful – andDescriptiveComplexity.cqDecoding, the computable decoding back, withDescriptiveComplexity.cqEvalWF_NP_complete, completeness on well-formed instances;DescriptiveComplexity.threeCol_fo_reduction_cqEval : ThreeCol ≤ᶠᵒ CQEval;DescriptiveComplexity.cqContainment_fo_reduction_cqEval : CQContainment ≤ᶠᵒ CQEval;DescriptiveComplexity.cqEval_fo_reduction_cqContainment : CQEval ≤ᶠᵒ CQContainment;DescriptiveComplexity.cqEval_NP_completeandDescriptiveComplexity.cqContainment_NP_complete.
Step 1: the concrete problem, in the user's own formalism #
A user of the library does not start from finite structures: they start from
concrete data. Here a Boolean conjunctive query over variables V and
constants C is a list of atoms – each argument in V ⊕ C – and a graph
database is a list of facts over the constants, with the textbook semantics
ConcreteQueryHolds (some assignment of the variables to constants sends
every atom to a fact). Nothing in this step mentions model theory; it is the
problem as a database theorist states it, and it is what the final
completeness theorem will be about, through the faithfulness theorem of
step 6.
Encoding this data into finite structures carries two obligations – the
encoding must preserve the meaning (semantic equivalence, step 6) and the
size (no padding, no compression, step 3) – and the machinery of
DescriptiveComplexity.Encoding makes both machine-checked. Stating the size
obligation needs the whole family of instances to be a single type, so the
data is also packaged as a record CQInstance of its dimensions and
contents. Two choices in the packaging are dictated by the machinery
itself, and both are the kind of judgement call the size bounds exist to
catch:
- Finite sets, not lists. With
List-valued atoms an instance could repeat one atom arbitrarily often: its declared size grows without bound while the encoded universe stays put, and the no-compression boundle_cardof step 3 would be simply false. Under set semantics the honest concrete object is a finite set of atoms anyway. - The size counts
nandm, not just the sets. The universe is the variables and constants: with2 ^ kvariables and a one-atom query, a size that only counted the sets would hide an exponential universe, and the no-padding boundcard_lewould be false.
The packaged type also carries m + 1 constants, so the nonempty-database
junk convention of the equivalence theorem (step 6) holds by construction.
The textbook semantics of a concrete Boolean conjunctive query q (a
list of binary atoms with arguments in V ⊕ C: variables to the left,
constants to the right) on a concrete graph database D (a list of facts
over the constants): some assignment of the variables to constants sends
every atom to a fact.
Equations
Instances For
Dependency graph
A packaged concrete evaluation instance: n query variables, m + 1
database constants, a finite set of query atoms over them, and a finite set
of database facts on the constants.
- vars : ℕ
The number of query variables.
- consts : ℕ
The number of constants, minus one: constants are
Fin (consts + 1), so the database domain is never empty. The query atoms, over variables and constants.
The database facts, over the constants.
Instances For
Dependency graph
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Dependency graph
The textbook size of a packaged instance: elements (variables and constants) plus atoms plus facts. This is the one audited line of the encoding – everything else is checked against it.
Equations
Instances For
Dependency graph
The textbook semantics of a packaged instance: ConcreteQueryHolds, with
the finite sets in place of lists.
Equations
Instances For
Dependency graph
Step 2: the vocabulary of evaluation instances #
An instance of the evaluation problem is a query and a database, packaged in a single finite structure. Elements of the structure play three roles: query variables (distinguished by a unary predicate), database elements, and constants – a constant is simply an element that is not marked as a variable and can appear both in query atoms and in database facts, which is how the two halves of the instance share constants. Two binary relations record the query atoms and the database facts.
As everywhere in the library, the language lives in Mathlib's
FirstOrder.Language namespace, next to Language.graph and
Language.order (a project-local Language namespace would shadow Mathlib's
under open Language).
Relation symbols of the language of BCQ evaluation instances.
- isVar : queryDbRel 1
isVar x: the elementxis a variable of the query. - atom : queryDbRel 2
atom x y: the query contains the atomE(x, y)(its arguments are variables or constants). - fact : queryDbRel 2
fact a b: the database contains the factE(a, b).
Instances For
Dependency graph
Dependency graph
Equations
- One or more equations did not get rendered due to their size.
- FirstOrder.Language.instDecidableEqQueryDbRel.decEq FirstOrder.Language.queryDbRel.atom FirstOrder.Language.queryDbRel.atom = isTrue FirstOrder.Language.instDecidableEqQueryDbRel.decEq._proof_2
- FirstOrder.Language.instDecidableEqQueryDbRel.decEq FirstOrder.Language.queryDbRel.fact FirstOrder.Language.queryDbRel.fact = isTrue FirstOrder.Language.instDecidableEqQueryDbRel.decEq._proof_5
Instances For
Dependency graph
The relational language of BCQ evaluation instances: a query and a database over a shared universe, with a unary predicate singling out the query variables and binary predicates for query atoms and database facts.
Equations
- FirstOrder.Language.queryDb = { Functions := fun (x : ℕ) => Empty, Relations := FirstOrder.Language.queryDbRel }
Instances For
Dependency graph
Dependency graph
The symbol for “is a query variable”.
Instances For
Dependency graph
The symbol for “is an atom of the query”.
Instances For
Dependency graph
The symbol for “is a fact of the database”.
Instances For
Dependency graph
Step 3: the encoding, size bounds discharged at construction #
With the vocabulary fixed, the packaged instances are encoded as
Language.queryDb-structures: universe Fin n ⊕ Fin (m + 1), relations
decided by membership in the packaged sets. The encoder cqRelBool is a
standalone, auditable def, and the bundle cqEncoding cannot be
constructed without discharging the two size bounds – the
representation-faithfulness obligation, closed here before anything is
proved about meaning (that is step 6, once the abstract semantics exists).
The encoder itself, standalone rather than inline in the bundle, so that
it can be audited in isolation: it elaborates as a plain def – an encoder
deciding an undecidable predicate could not, the compiler would demand
noncomputable – and it genuinely runs (the #guards below). Its
#print axioms still cites the classical axioms, harmlessly: Finset
membership is decided through Multiset quotients, whose instances cite them
in proof positions only – executability is witnessed by execution, not by
the axiom report.
Equations
- One or more equations did not get rendered due to their size.
- DescriptiveComplexity.cqRelBool i FirstOrder.Language.queryDbRel.isVar = fun (x : Fin 1 → Fin i.vars ⊕ Fin (i.consts + 1)) => (x 0).isLeft
- DescriptiveComplexity.cqRelBool i FirstOrder.Language.queryDbRel.atom = fun (x : Fin 2 → Fin i.vars ⊕ Fin (i.consts + 1)) => decide ((x 0, x 1) ∈ i.atoms)
Instances For
Dependency graph
The encoding of packaged instances by Language.queryDb-structures:
universe Fin n ⊕ Fin (m + 1), relations decided by membership in the
packaged sets (cqRelBool, a Bool-valued query/database structure).
The bounds record that nothing blows up and nothing is compressed.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Step 4: semantics #
RelMap-based shorthands first: they keep every later statement readable
(compare MGAdj and MGMarked in Problems/CliqueFamily/Defs.lean).
x is a variable of the query.
Equations
Instances For
Dependency graph
E(x, y) is an atom of the query.
Equations
Instances For
Dependency graph
E(a, b) is a fact of the database (raw: no constraint on a, b).
Equations
Instances For
Dependency graph
A genuine database edge: a fact both of whose endpoints are database elements (i.e. not query variables). Facts violating this are representation junk and are ignored by the semantics.
Equations
Instances For
Dependency graph
The semantic core is satisfaction of a conjunctive query in a database, which we set up generically – for an arbitrary “variable” predicate and “atom” relation on the instance, and an arbitrary external database – because the very same notion drives evaluation (database inside the instance), containment (database quantified over), and the homomorphism criterion (database = canonical instance). Factoring it out is what will later make the Chandra–Merlin theorem a ten-line proof.
A database over a universe U is a binary relation F on U; since
instance elements that are not variables (the constants) must denote fixed
database values, a database additionally comes with an interpretation
ι : A → U of the instance elements (only its values on non-variables ever
matter). A valuation witnessing satisfaction maps every element to U,
agreeing with ι on non-variables and sending every atom to an F-edge.
Note the standing conventions of this formalization, both harmless for instances that faithfully encode actual queries:
- valuations are total, so a query variable that occurs in no atom is mapped somewhere but unconstrained (in a real BCQ every variable occurs in an atom, so this is a junk-only concern);
ιbeing total forces the database universe to be nonempty as soon as the instance is – the usual nonempty-universe convention of finite model theory, applied to the quantified databases as well.
The conjunctive query with variables VarP and atoms AtomP (over
instance elements A) is satisfied in the database F on universe U,
where ι fixes the denotation of the non-variables: some valuation extends
ι and maps every atom to a database edge.
Equations
- DescriptiveComplexity.SatisfiedIn VarP AtomP F ι = ∃ (v : A → U), (∀ (x : A), ¬VarP x → v x = ι x) ∧ ∀ (x y : A), AtomP x y → F (v x) (v y)
Instances For
Dependency graph
The homomorphism condition: satisfaction in a database carried by the instance's own universe, with every non-variable denoting itself. This single notion underlies both problems below.
Equations
- DescriptiveComplexity.CQHom VarP AtomP FactP = DescriptiveComplexity.SatisfiedIn VarP AtomP FactP id
Instances For
Dependency graph
The homomorphism condition transports along an equivalence commuting with the three predicates. This is the generic workhorse for the isomorphism-invariance proofs (step 5) and for the dimension-1, single-tag reduction of step 12.
Dependency graph
The homomorphism condition transports along an equivalence, iff version.
Dependency graph
The query of an evaluation instance holds in its database: there is a valuation of the elements, fixing the non-variables, that maps every query atom to a genuine database edge. This is the classical semantics of Boolean conjunctive queries, phrased as a homomorphism into the database half of the instance.
Equations
Instances For
Dependency graph
Step 5: isomorphism-invariance and the bundled problem #
A DecisionProblem requires isomorphism-invariance. Thanks to the generic
transport lemma this is a matter of transporting the three RelMap
predicates along the isomorphism, for which the library provides
DescriptiveComplexity.relMap_equiv₁ / relMap_equiv₂ (in Interpretation.lean).
Query evaluation is isomorphism-invariant.
Dependency graph
BCQ evaluation, as a decision problem on Language.queryDb-structures:
does the query of the instance hold in its database?
Equations
- DescriptiveComplexity.CQEval = { Holds := fun (A : Type) (inst : FirstOrder.Language.queryDb.Structure A) => DescriptiveComplexity.QueryHolds A, iso_invariant := ⋯ }
Instances For
Dependency graph
Step 6: faithfulness – the encoded problem is the concrete one #
The bridge between steps 1 and 5: the abstract semantics of the encoded structure agrees, instance by instance, with the textbook semantics of the data; otherwise the complexity results to come would be about the wrong predicate. This is a theorem, so Lean holds you to it – get the encoding subtly wrong and the proof simply does not close.
The equivalence is proved in two moves. First, in the generic V C setting
of step 1: each pair is encoded on the universe V ⊕ C by
queryDbStructure, and the round-trip theorem
concreteQueryHolds_iff_queryHolds relates the abstract semantics of step 4
to the textbook one on every such structure. (Its Nonempty C hypothesis is
the junk convention of step 4 surfacing: a variable occurring in no atom is
unconstrained abstractly but must still be assigned a constant concretely –
for genuine BCQs over a nonempty database domain nothing is lost, and the
packaged type of step 1 discharges the hypothesis by construction.) Then the
packaged encoding is reduced to that generic statement, giving
cqEncoding_faithful: obligation (1) of step 1, against the bundle whose
construction already discharged obligation (2).
The Language.queryDb-structure encoding a concrete instance: universe
V ⊕ C, the variables being the left summands, with the atoms of q and
the facts of D.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
The encoding is faithful: the abstract semantics QueryHolds of the
encoded structure agrees with the textbook semantics of the concrete query
on the concrete database.
Dependency graph
The packaged encoding is faithful: the abstract problem CQEval
computes the textbook semantics on every encoded instance. This is obligation
(1) of step 1, proved against the bundled encoding – whose construction
already discharged obligation (2).
Dependency graph
The worked two-fact instance of step 6, packaged: one variable,
two constants, the query ∃ x, E(x, c₀) ∧ E(c₀, x), the database
{E(c₁, c₀), E(c₀, c₁)}.
Equations
Instances For
Dependency graph
The encoder is a computation, so it can also be run: the #guards below
evaluate the encoded relations of the worked instance and check them against
the hand computation – the cheapest guard against an encoding that is
faithful and size-honest but simply not the one the author meant. That they
compile at all is itself a check: an encoder whose data decided an
undecidable predicate would be rejected by the compiler (see the hygiene
section of DescriptiveComplexity/Encoding.lean).
Faithfulness reads membership results into the concrete world; hardness
results also need a decoding direction: the abstract problem must not be hard
only on junk structures the encoding never produces. Following
DescriptiveComplexity/Decoding.lean, this takes two steps, both cheap here.
Well-formedness. The one junk convention that matters for decoding is a
structure with no constant at all (the abstract semantics can satisfy a
query on it that no concrete assignment – needing a constant to map
variables to – satisfies). The sentence cqWFSentence, "some element is not
a variable", cuts these out; read as a DecisionProblem (via
DecisionProblem.ofSentence) it restricts evaluation to the well-formed
problem, whose completeness is step 9's cqEvalWF_NP_complete. Junk facts
(touching a variable) need no well-formedness at all: DbEdge guards both
endpoints with ¬QVar, so the decoder below simply drops them, invisibly to
the semantics.
The decoder. The computable
cqDecode : FinPresentation Language.queryDb → Option CQInstance enumerates
the variables and the constants of a presented structure
(Finset.orderIsoOfFin supplies the renumbering) and reads the atoms and
facts through it, returning none exactly when there is no constant.
Soundness and totality assemble it into DescriptiveComplexity.cqDecoding,
and – like the encoder – it runs: see the #guards below. An ∃-only
decoding statement would be classically near-vacuous (case on the abstract
truth value); the bundled computation is what makes the decoding direction
mean something – see the module docstring of
DescriptiveComplexity/Decoding.lean.
Well-formedness of an evaluation instance: some element is a constant. The one condition the decoder needs.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Dependency graph
The variable elements of a presented instance.
Equations
- DescriptiveComplexity.cqVars S = {x : Fin S.card | S.relBool FirstOrder.Language.qdbIsVar ![x] = true}
Instances For
Dependency graph
The constant elements of a presented instance.
Equations
Instances For
Dependency graph
Dependency graph
Dependency graph
The renumbering of a presented instance: variables to the left, constants to the right, each in order.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Dependency graph
The decoder: enumerate variables and constants, read the atoms and facts
through the renumbering; none exactly when the instance has no constant.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Dependency graph
Dependency graph
The computable decoding of well-formed evaluation instances. Together
with cqEncoding_faithful it closes the loop between the concrete and the
abstract problem: encoded instances are equidecided (step 6 above), and every
well-formed presented structure decodes to an equidecided concrete instance
(Decoding.exists_conc_iff).
Equations
Instances For
Dependency graph
A presented three-element structure: element 0 a variable, elements
1, 2 constants, one atom E(0, 1), one fact E(1, 2).
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Step 7: membership in NP #
NP is defined in this library as Σ₁ second-order definability (Fagin's
theorem), so membership means exhibiting a second-order sentence: guess an
object-level certificate, check it with a first-order kernel. The natural
certificate here is (the graph of) the valuation: a single binary relation
variable H, with H x u read as “x is mapped to u”.
Since a raw guessed relation need not be the graph of a function, the kernel does not try to say so; it checks instead that
- every possible image pair of every atom is a database edge, where
uis a possible image ofxifH x uholds andxis a variable, oru = xandxis not (so non-variables are their own images andHjunk on non-variables is ignored); and - every variable has at least one
H-image;
which is equivalent to the existence of a valuation (pick any image for each variable: by 1 all image choices work). This “all images are good, and images exist” trick avoids expressing functionality in the kernel and is a reusable pattern for guessing functions by relations.
The construction mirrors sat_sigmaSODefinable (Problems/Sat.lean): a
SOBlock for the quantifier block, an object-level kernel over the sum
vocabulary, one realization lemma, and the definability theorem.
The single existential second-order block of the Σ₁ definition of BCQ
evaluation: one binary relation variable, the (graph of the) valuation.
Equations
Instances For
Dependency graph
The symbol of the guessed-valuation relation variable.
Instances For
Dependency graph
The vocabulary of the kernel: evaluation instances together with the guessed-valuation relation variable.
Equations
Instances For
Dependency graph
The symbol for “is a query variable” in the kernel's vocabulary.
Instances For
Dependency graph
The symbol for “is an atom of the query” in the kernel's vocabulary.
Instances For
Dependency graph
The symbol for “is a fact of the database” in the kernel's vocabulary.
Instances For
Dependency graph
The guessed-valuation symbol in the kernel's vocabulary.
Instances For
Dependency graph
The kernel formula “kv j is a possible image of kv i”: an H-image
if kv i is a query variable, kv i itself otherwise.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
First kernel conjunct: for all x y u v, if E(x, y) is an atom and
u, v are possible images of x, y, then E(u, v) is a fact between
two database elements.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Second kernel conjunct: every query variable has at least one
H-image.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
The first-order kernel of the Σ₁ definition of BCQ evaluation.
Equations
Instances For
Dependency graph
BCQ evaluation is Σ₁-definable: existentially quantify the graph of
a valuation and check it first-order. Since NP is defined as
Σ₁-definability, this is membership in NP.
Dependency graph
Dependency graph
Step 8: NP-hardness, by reduction from 3-colorability #
The hardness half is a first-order reduction from a problem the catalog
already knows to be NP-hard. The classical source for evaluation is graph
coloring: a graph G is 3-colorable iff there is a graph homomorphism
G → K₃, i.e. iff the canonical query of G (one variable per vertex, one
atom per edge) holds in the database K₃.
The interpretation must build both halves of the evaluation instance from the
single input graph, which is exactly what the tags of the framework are
for: a tag qvtx for the query side (one variable per vertex) and one tag
per color for the database side. There is a wrinkle worth internalizing: the
interpreted universe is Tag × V, so the database side consists of |V|
copies of each color, not of K₃ itself. Junk of this kind is unavoidable in
a tagged interpretation, and the standard cure is to make it harmless
rather than to eliminate it: connecting all copies of distinct colors yields
a complete tripartite graph, which is hom-equivalent to K₃, so the query
holds iff G is 3-colorable all the same.
All defining formulas are quantifier-free, so the reduction is a quantifier-free (and order-free) one, the weakest reduction notion in common use in descriptive complexity.
Tags for the interpretation of evaluation instances in graphs.
- qvtx : ColEvalTag
(qvtx, u): the query variable associated to the vertexu. - color : Fin 3 → ColEvalTag
(color c, u): a database element of colorc(one copy per vertex; all copies of distinct colors are connected by facts).
Instances For
Dependency graph
Equations
- DescriptiveComplexity.instDecidableEqColEvalTag.decEq DescriptiveComplexity.ColEvalTag.qvtx DescriptiveComplexity.ColEvalTag.qvtx = isTrue ⋯
- DescriptiveComplexity.instDecidableEqColEvalTag.decEq DescriptiveComplexity.ColEvalTag.qvtx (DescriptiveComplexity.ColEvalTag.color a) = isFalse ⋯
- DescriptiveComplexity.instDecidableEqColEvalTag.decEq (DescriptiveComplexity.ColEvalTag.color a) DescriptiveComplexity.ColEvalTag.qvtx = isFalse ⋯
- DescriptiveComplexity.instDecidableEqColEvalTag.decEq (DescriptiveComplexity.ColEvalTag.color a) (DescriptiveComplexity.ColEvalTag.color b) = if h : a = b then h ▸ isTrue ⋯ else isFalse ⋯
Instances For
Dependency graph
Dependency graph
Dependency graph
Dependency graph
Defining formula for isVar: exactly the qvtx-tagged elements.
Equations
Instances For
Dependency graph
Defining formula for atom: the canonical query of the graph – one atom
per (directed) edge, between the corresponding query variables.
Equations
- One or more equations did not get rendered due to their size.
- DescriptiveComplexity.cevAtomFormula x✝¹ x✝ = ⊥
Instances For
Dependency graph
Defining formula for fact: all pairs of database elements of distinct
colors (a complete tripartite graph, hom-equivalent to K₃).
Equations
Instances For
Dependency graph
The first-order interpretation producing, from a graph, the evaluation
instance “does the canonical query of the graph hold in K₃?”.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Dependency graph
Dependency graph
Dependency graph
The color carried by a database-side tag (junk value 0 on the
query-side tag).
Equations
Instances For
Dependency graph
Correctness of the reduction: a graph is 3-colorable iff the canonical query holds in the interpreted database.
Dependency graph
3-colorability FO-reduces to BCQ evaluation – the fo_reduction
theorem for the hardness half.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
The reduction is even quantifier-free.
Dependency graph
Step 9: completeness of evaluation #
Membership and hardness combine into the completeness theorem. This is the end of the recipe for a single problem; the remaining steps treat containment by reusing evaluation instead of repeating steps 7 and 8 from scratch.
BCQ evaluation is NP-hard: 3-colorability, which is NP-hard, FO-reduces to it.
Dependency graph
BCQ evaluation (combined complexity) is NP-complete (Chandra–Merlin).
Dependency graph
The image of the hardness reduction is well-formed: interpreted instances always carry a constant (any database-side copy).
Dependency graph
Well-formed BCQ evaluation is NP-complete: evaluation restricted to
the well-formed instances of step 6. Both halves are one-line upgrades of the
plain completeness proof – the same reduction with its image lemma
(FOReduction.withInvariant), the same kernel with the sentence conjoined
(SigmaSODefinable.inf_ofSentence) – the pattern for reading hardness on
non-junk instances (DescriptiveComplexity/Decoding.lean).
Dependency graph
Step 10: containment – vocabulary, semantics, and the Chandra–Merlin theorem #
An instance of the containment problem is a pair of queries over a shared universe: unary predicates mark the variables of the left and of the right query, binary relations record their atoms, and the remaining elements are shared constants. The problem asks whether the left query is contained in the right one: every database satisfying the left query satisfies the right one.
Unlike evaluation, the defining property quantifies over all databases –
this is where the generic SatisfiedIn with an external database pays off.
Note the junk convention it implies: in an atom of one query, an element
marked only as a variable of the other query is not a constant, so it acts
as an existential variable of both queries. Well-formed instances (where each
query's atoms only involve its own variables and constants) are unaffected.
The key structural result is the Chandra–Merlin theorem: containment holds iff there is a homomorphism from the right query into the canonical database of the left one – the instance universe itself, with the left atoms as facts and every element denoting itself. Both directions are short: the canonical database trivially satisfies the left query, and conversely a homomorphism composes with any satisfying valuation. This theorem is what turns the ∀-databases semantics into an ∃-certificate condition, i.e. into something NP-shaped.
Relation symbols of the language of query pairs.
- leftVar : queryPairRel 1
leftVar x: the elementxis a variable of the left query. - rightVar : queryPairRel 1
rightVar x: the elementxis a variable of the right query. - leftAtom : queryPairRel 2
leftAtom x y: the left query contains the atomE(x, y). - rightAtom : queryPairRel 2
rightAtom x y: the right query contains the atomE(x, y).
Instances For
Dependency graph
Dependency graph
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
The relational language of pairs of conjunctive queries over a shared universe of variables and constants.
Equations
- FirstOrder.Language.queryPair = { Functions := fun (x : ℕ) => Empty, Relations := FirstOrder.Language.queryPairRel }
Instances For
Dependency graph
Dependency graph
The symbol for “is a variable of the left query”.
Instances For
Dependency graph
The symbol for “is a variable of the right query”.
Instances For
Dependency graph
The symbol for “is an atom of the left query”.
Instances For
Dependency graph
The symbol for “is an atom of the right query”.
Instances For
Dependency graph
x is a variable of the left query.
Equations
Instances For
Dependency graph
x is a variable of the right query.
Equations
Instances For
Dependency graph
E(x, y) is an atom of the left query.
Equations
Instances For
Dependency graph
E(x, y) is an atom of the right query.
Equations
Instances For
Dependency graph
x is a variable of either query; the non-PairVar elements are the
shared constants, whose denotation every database fixes.
Equations
Instances For
Dependency graph
The left query is contained in the right one: every database (over any universe, with any interpretation of the constants) satisfying the left query satisfies the right query.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
The Chandra–Merlin theorem: containment holds iff there is a homomorphism from the right query to the canonical database of the left one – i.e. a map of the universe to itself, fixing the constants, that sends every right atom to a left atom. The forward direction instantiates containment at the canonical database (which satisfies the left query via the identity valuation); the backward direction composes the homomorphism with any satisfying valuation.
Dependency graph
Containment is isomorphism-invariant: via the Chandra–Merlin theorem, it suffices to transport the homomorphism criterion, which the generic transport lemma of step 4 does. (Transporting the ∀-databases definition directly would also work, but reusing the homomorphism form is shorter.)
Dependency graph
BCQ containment, as a decision problem on
Language.queryPair-structures: is the left query contained in the right
one?
Equations
- DescriptiveComplexity.CQContainment = { Holds := fun (A : Type) (inst : FirstOrder.Language.queryPair.Structure A) => DescriptiveComplexity.QueryContained A, iso_invariant := ⋯ }
Instances For
Dependency graph
Step 11: containment is in NP, by reduction to evaluation #
By Chandra–Merlin, containment is evaluation of the right query in the
canonical database of the left one – so containment FO-reduces to
evaluation, and membership in NP follows from cqEval_mem_NP through
ComplexityClass.mem_of_foReduction. No second kernel needed.
The interpretation must produce a well-formed evaluation instance from an arbitrary query-pair structure, and this forces a design decision worth dwelling on, because it recurs in every reduction between problems whose semantics have different junk conventions. In the homomorphism criterion the canonical database consists of all elements (frozen variables and constants alike), while in an evaluation instance the database elements are exactly the non-variables. A single copy of the universe cannot be split both ways, so the interpretation uses two tags – a query side and a database side – and routes each atom endpoint to the query side if it is a variable of either query (recall the junk convention of step 10) and to the database side otherwise. The database side carries the left atoms as facts, on all elements. All formulas remain quantifier-free.
Tags for the interpretation of evaluation instances in query pairs: a query side and a database side (the canonical database of the left query).
- query : PairTag
(query, x): the elementxviewed as part of the right query. - db : PairTag
(db, x): the elementxviewed as part of the canonical database of the left query.
Instances For
Dependency graph
Dependency graph
Dependency graph
Dependency graph
Defining formula for isVar: on the query side, the variables of either
query; nothing on the database side.
Equations
Instances For
Dependency graph
Defining formula for atom: the right atoms, each endpoint routed to the
query side if it is a variable and to the database side if it is a
constant.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Defining formula for fact: the left atoms, on the database side.
Equations
Instances For
Dependency graph
The first-order interpretation producing, from a query pair, the evaluation instance “does the right query hold in the canonical database of the left one?”.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Dependency graph
Dependency graph
Dependency graph
Correctness of containmentToEval: containment holds iff the interpreted
evaluation instance is a yes-instance. Both sides are homomorphism
conditions (containment via the Chandra–Merlin theorem), and the proof
translates homomorphisms back and forth across the routing of the
interpretation.
Dependency graph
BCQ containment FO-reduces to BCQ evaluation – the Chandra–Merlin theorem, in reduction form: evaluate the right query in the canonical database of the left one.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
BCQ containment is in NP: it FO-reduces to BCQ evaluation, which is in NP.
Dependency graph
Step 12: containment is NP-hard, by reduction from evaluation #
The reverse reduction expresses the other classical half of the
correspondence: a database is just a conjunctive query with no variables.
An evaluation instance (q, D) becomes the pair “(the canonical query of
D) ⊆ q”: the left query has no variables and one atom per genuine
database edge, the right query is q itself. Every element keeps its role,
so a single tag and dimension 1 suffice, and correctness reduces – through
Chandra–Merlin on the interpreted side – to comparing two homomorphism
conditions over universes identified by FOInterpretation.mapEquivSelf.
The first-order interpretation producing, from an evaluation instance, the containment instance “(the database, viewed as a variable-free query) is contained in the query”.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Dependency graph
Dependency graph
Dependency graph
Dependency graph
Dependency graph
Correctness of evalToContainment: the query holds in the database iff
the interpreted containment instance is a yes-instance.
Dependency graph
BCQ evaluation FO-reduces to BCQ containment: a database is a variable-free conjunctive query.
Equations
- DescriptiveComplexity.cqEval_fo_reduction_cqContainment = { Tag := Unit, tagFinite := ⋯, tagNonempty := ⋯, dim := 1, toInterpretation := DescriptiveComplexity.evalToContainment, correct := ⋯ }
Instances For
Dependency graph
BCQ containment is NP-hard: BCQ evaluation, which is NP-hard, FO-reduces to it.
Dependency graph
BCQ containment is NP-complete (Chandra–Merlin).
Dependency graph
Where to go from here #
The two problems above, with their four reductions, exercise every part of the recipe; a few directions the reader can take next, in rough order of effort:
- other schemas: redo the development for a schema with several relations
of higher arity – the vocabulary grows, the proofs do not change shape
(atoms of arity
kneed interpreted elements of dimensionk, i.e.dim > 1interpretations as inProblems/ThreeColorability/ToSat.lean); - quantifier-free status of the containment reductions: state and prove
IsQuantifierFreeforcontainmentToEvalandevalToContainment, in the style ofthreeColToCQEval_isQuantifierFree; - a concrete bridge for containment: encode a concrete pair of queries as
a
Language.queryPair-structure and prove the analogue ofconcreteQueryHolds_iff_queryHolds, tyingQueryContainedto a list-of-atoms statement of containment; - query equivalence: two-sided containment; its NP-completeness follows from this file's results with a pair of FO reductions;
- acyclic-query evaluation: the tractable fragment (Yannakakis); its
membership statement is a
DescriptiveComplexity.PTIMEone, hence an SO-Horn definition (DescriptiveComplexity.SigmaSOHornDefinable).