Documentation

DescriptiveComplexity.Examples.ConjunctiveQueries

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):

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:

  1. Vocabulary: a relational FirstOrder.Language whose finite structures are the problem instances.
  2. 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.
  3. Invariance: the predicate is isomorphism-invariant, giving a bundled DecisionProblem.
  4. 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.
  5. Hardness: an FO reduction from an NP-hard problem of the catalog.
  6. 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:

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:

The packaged type also carries m + 1 constants, so the nonempty-database junk convention of the equivalence theorem (step 6) holds by construction.

def DescriptiveComplexity.ConcreteQueryHolds {V C : Type} (q : List ((V C) × (V C))) (D : List (C × C)) :

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.

    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 element x is a variable of the query.

            • atom : queryDbRel 2

              atom x y: the query contains the atom E(x, y) (its arguments are variables or constants).

            • fact : queryDbRel 2

              fact a b: the database contains the fact E(a, b).

            Instances For
              Dependency graph
              Dependency graph
              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
              Instances For
                Dependency graph
                Dependency graph
                @[reducible, inline]

                The symbol for “is a query variable”.

                Equations
                Instances For
                  Dependency graph
                  @[reducible, inline]

                  The symbol for “is an atom of the query”.

                  Equations
                  Instances For
                    Dependency graph
                    @[reducible, inline]

                    The symbol for “is a fact of the database”.

                    Equations
                    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
                      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).

                          Dependency graph
                          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:

                              def DescriptiveComplexity.SatisfiedIn {A : Type} (VarP : AProp) (AtomP : AAProp) {U : Type} (F : UUProp) (ι : AU) :

                              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
                              Instances For
                                Dependency graph
                                def DescriptiveComplexity.CQHom {A : Type} (VarP : AProp) (AtomP FactP : AAProp) :

                                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
                                Instances For
                                  Dependency graph
                                  theorem DescriptiveComplexity.CQHom.of_equiv {A B : Type} (u : A B) {VarA : AProp} {AtomA FactA : AAProp} {VarB : BProp} {AtomB FactB : BBProp} (hVar : ∀ (a : A), VarA a VarB (u a)) (hAtom : ∀ (a a' : A), AtomA a a' AtomB (u a) (u a')) (hFact : ∀ (a a' : A), FactA a a' FactB (u a) (u a')) (h : CQHom VarA AtomA FactA) :
                                  CQHom VarB AtomB FactB

                                  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
                                  theorem DescriptiveComplexity.CQHom.equiv_iff {A B : Type} (u : A B) {VarA : AProp} {AtomA FactA : AAProp} {VarB : BProp} {AtomB FactB : BBProp} (hVar : ∀ (a : A), VarA a VarB (u a)) (hAtom : ∀ (a a' : A), AtomA a a' AtomB (u a) (u a')) (hFact : ∀ (a a' : A), FactA a a' FactB (u a) (u a')) :
                                  CQHom VarA AtomA FactA CQHom VarB AtomB FactB

                                  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).

                                    Dependency graph

                                    BCQ evaluation, as a decision problem on Language.queryDb-structures: does the query of the instance hold in its database?

                                    Equations
                                    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).

                                      @[instance_reducible]

                                      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.queryDbOption 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
                                            Dependency graph
                                            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

                                                    1. every possible image pair of every atom is a database edge, where u is a possible image of x if H x u holds and x is a variable, or u = x and x is not (so non-variables are their own images and H junk on non-variables is ignored); and
                                                    2. 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
                                                      Dependency graph
                                                      @[reducible, inline]

                                                      The vocabulary of the kernel: evaluation instances together with the guessed-valuation relation variable.

                                                      Equations
                                                      Instances For
                                                        Dependency graph
                                                        @[reducible, inline]

                                                        The symbol for “is a query variable” in the kernel's vocabulary.

                                                        Equations
                                                        Instances For
                                                          Dependency graph
                                                          @[reducible, inline]

                                                          The symbol for “is an atom of the query” in the kernel's vocabulary.

                                                          Equations
                                                          Instances For
                                                            Dependency graph
                                                            @[reducible, inline]

                                                            The symbol for “is a fact of the database” in the kernel's vocabulary.

                                                            Equations
                                                            Instances For
                                                              Dependency graph
                                                              @[reducible, inline]

                                                              The guessed-valuation symbol in the kernel's vocabulary.

                                                              Equations
                                                              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

                                                                        BCQ evaluation is in NP.

                                                                        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 vertex u.

                                                                        • color : Fin 3ColEvalTag

                                                                          (color c, u): a database element of color c (one copy per vertex; all copies of distinct colors are connected by facts).

                                                                        Instances For
                                                                          Dependency graph
                                                                          Dependency graph
                                                                          Dependency graph
                                                                          Dependency graph
                                                                          Dependency graph
                                                                          Dependency graph

                                                                          Defining formula for atom: the canonical query of the graph – one atom per (directed) edge, between the corresponding query variables.

                                                                          Equations
                                                                          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
                                                                                @[simp]
                                                                                theorem DescriptiveComplexity.cev_fact_iff {V : Type} [FirstOrder.Language.graph.Structure V] (t t' : ColEvalTag) (w w' : Fin 1V) :
                                                                                DbFact (t, w) (t', w') ∃ (c : Fin 3) (c' : Fin 3), t = ColEvalTag.color c t' = ColEvalTag.color c' c c'
                                                                                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
                                                                                    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.

                                                                                    Instances For
                                                                                      Dependency graph
                                                                                      Dependency graph
                                                                                      def FirstOrder.Language.instDecidableEqQueryPairRel.decEq {a✝ : } (x✝ x✝¹ : queryPairRel a✝) :
                                                                                      Decidable (x✝ = x✝¹)
                                                                                      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
                                                                                        Instances For
                                                                                          Dependency graph
                                                                                          Dependency graph
                                                                                          @[reducible, inline]

                                                                                          The symbol for “is a variable of the left query”.

                                                                                          Equations
                                                                                          Instances For
                                                                                            Dependency graph
                                                                                            @[reducible, inline]

                                                                                            The symbol for “is a variable of the right query”.

                                                                                            Equations
                                                                                            Instances For
                                                                                              Dependency graph
                                                                                              @[reducible, inline]

                                                                                              The symbol for “is an atom of the left query”.

                                                                                              Equations
                                                                                              Instances For
                                                                                                Dependency graph
                                                                                                @[reducible, inline]

                                                                                                The symbol for “is an atom of the right query”.

                                                                                                Equations
                                                                                                Instances For
                                                                                                  Dependency graph
                                                                                                  Dependency graph
                                                                                                  Dependency graph
                                                                                                  Dependency graph
                                                                                                  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
                                                                                                      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 element x viewed as part of the right query.

                                                                                                        • db : PairTag

                                                                                                          (db, x): the element x viewed as part of the canonical database of the left query.

                                                                                                        Instances For
                                                                                                          Dependency graph
                                                                                                          @[instance_reducible]
                                                                                                          Equations
                                                                                                          Dependency graph
                                                                                                          Dependency graph
                                                                                                          Dependency graph
                                                                                                          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
                                                                                                            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
                                                                                                              @[simp]
                                                                                                              theorem DescriptiveComplexity.ctev_atom_iff {A : Type} [FirstOrder.Language.queryPair.Structure A] (t t' : PairTag) (w w' : Fin 1A) :
                                                                                                              QAtom (t, w) (t', w') RAtom (w 0) (w' 0) (t = PairTag.query PairVar (w 0)) (t' = PairTag.query PairVar (w' 0))
                                                                                                              Dependency graph
                                                                                                              @[simp]
                                                                                                              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
                                                                                                                  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: