ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
probability_evaluate.cpp
Go to the documentation of this file.
1/**
2 * @file probability_evaluate.cpp
3 * @brief SQL function @c provsql.probability_evaluate() – probabilistic circuit evaluation.
4 *
5 * Implements @c provsql.probability_evaluate(), which computes the
6 * probability that a provenance circuit evaluates to @c true under the
7 * tuple-independent probabilistic-database model.
8 *
9 * The @p method argument selects the computation algorithm:
10 * - @c "possible-worlds": exact enumeration of all 2^n worlds.
11 * - @c "monte-carlo": approximate via random sampling (fast, inexact).
12 * - @c "weightmc": approximate using the @c weightmc model counter.
13 * - @c "tree-decomposition": exact via tree-decomposition-based d-DNNF.
14 * - @c "independent": exact evaluation for read-once circuits and circuits whose
15 * sharing is certified.
16 * - @c "inversion-free": exact via the structured-d-DNNF builder over the
17 * query-derived order; errors unless the root carries an inversion-free
18 * certificate. The default method also tries it (after @c "independent")
19 * when a certificate is present.
20 * - Any external compiler name (@c "d4", @c "c2d", @c "minic2d", @c "dsharp").
21 *
22 * A SIGINT signal sets a process-local flag that causes the evaluation
23 * to abort and return @c NULL (used when the user cancels a long-running
24 * probability computation).
25 */
26extern "C" {
27#include "postgres.h"
28#include "fmgr.h"
29#include "catalog/pg_type.h"
30#include "miscadmin.h"
31#include "storage/latch.h"
32#include "utils/uuid.h"
33#include "executor/spi.h"
34#include "funcapi.h" // get_call_result_type, BlessTupleDesc
35#include "access/htup_details.h" // heap_form_tuple
36#include "provsql_shmem.h"
37#include "provsql_utils.h"
38#include "utils/guc.h"
39
40PG_FUNCTION_INFO_V1(probability_evaluate);
41PG_FUNCTION_INFO_V1(probability_bounds);
42}
43
44#include "c_cpp_compatibility.h"
45#include <set>
46#include <stack>
47#include <map>
48#include <unordered_map>
49#include <limits>
50#include <chrono>
51#include <vector>
52#include <algorithm>
53#include <cmath>
54#include <optional>
55#include <csignal>
56#include <string>
57#include <sstream>
58#include <cctype>
59
60#include "BooleanCircuit.h"
61#include "CircuitFromMMap.h"
62#include "provsql_interrupt.h"
63#include "GenericCircuit.h"
64#include "FixSystemGraph.h"
65#include "AnalyticEvaluator.h"
66#include "CountCmpEvaluator.h"
67#include "MinMaxCmpEvaluator.h"
68#include "SumCmpEvaluator.h"
70#include "HybridEvaluator.h"
71#include "RangeCheck.h"
72#include "MonteCarloSampler.h"
73#include "ProbCache.h"
74#include "external_tool.h"
76#include "TreeDecomposition.h"
77#include "StructuredDNNF.h"
78#include "DTree.h"
79#include "ProbabilityMethod.h"
81#include "having_semantics.hpp"
82#include "provsql_mmap.h"
83#include "safe_query_cert.h"
84#include "provsql_utils_cpp.h"
85#include "tool_registry_sync.h"
86#include "semiring/BoolExpr.h"
87#include "semiring/Semiring.h"
88#include "mobius_evaluate.h"
89
90using namespace std;
91
92namespace {
93
94// ---------------------------------------------------------------------------
95// Möbius-route probability sweep (safe-UCQ Möbius-inversion route).
96//
97// The Möbius compiler (mobius_evaluate.cpp) materialises a circuit rooted at a
98// gate_mobius signed combination over certified-independent Boolean islands.
99// Its probability is a single linear sweep: the Boolean islands evaluate
100// read-once (independent OR / AND), and at each gate_mobius the children's
101// probabilities are summed with the stored integer coefficients. gate_mobius
102// nodes nest (an inner MobiusStep is a child of an outer separator's
103// independent-OR), so one unified recursion walks the whole mixed circuit.
104// ---------------------------------------------------------------------------
105double mobiusEvalRec(GenericCircuit &gc, gate_t g, std::map<gate_t,double> &memo)
106{
107 auto it = memo.find(g);
108 if(it != memo.end()) return it->second;
109 CHECK_FOR_INTERRUPTS();
110 double r;
111 switch(gc.getGateType(g)) {
112 case gate_input: r = gc.getProb(g); break;
113 case gate_one: r = 1.0; break;
114 case gate_zero: r = 0.0; break;
115 case gate_times: {
116 r = 1.0;
117 for(gate_t c : gc.getWires(g)) r *= mobiusEvalRec(gc, c, memo);
118 break;
119 }
120 case gate_plus: { // independent OR (read-once by construction)
121 double pn = 1.0;
122 for(gate_t c : gc.getWires(g)) pn *= (1.0 - mobiusEvalRec(gc, c, memo));
123 r = 1.0 - pn;
124 break;
125 }
126 case gate_monus: { // monus(one, x) = NOT x
127 const auto &w = gc.getWires(g);
128 if(w.size()!=2)
129 throw CircuitException("mobius: malformed monus gate");
130 r = mobiusEvalRec(gc, w[0], memo) - mobiusEvalRec(gc, w[1], memo);
131 if(r < 0.) r = 0.;
132 break;
133 }
134 case gate_mobius: { // signed Möbius combination
135 const auto &w = gc.getWires(g);
136 const std::string extra = gc.getExtra(g);
137 // extra is a space-separated list of "uuid:coeff" (coefficients keyed by
138 // child UUID, so wire order / dedup do not matter), plus an optional
139 // "L:<uuid>" naming the literal-lineage child, which the probability
140 // shortcut ignores (it is there only for the non-probability evaluators).
141 std::map<std::string,long> co;
142 std::string lineage;
143 {
144 std::size_t i = 0;
145 while(i < extra.size()) {
146 while(i < extra.size() && (extra[i]==' '||extra[i]=='\t')) ++i;
147 if(i >= extra.size()) break;
148 std::size_t j = i;
149 while(j < extra.size() && extra[j]!=' ' && extra[j]!='\t') ++j;
150 const std::string tok = extra.substr(i, j-i);
151 if(tok.size()>2 && tok[0]=='L' && tok[1]==':')
152 lineage = tok.substr(2);
153 else {
154 const std::size_t colon = tok.rfind(':');
155 if(colon != std::string::npos)
156 co[tok.substr(0,colon)] =
157 std::strtol(tok.substr(colon+1).c_str(), nullptr, 10);
158 }
159 i = j;
160 }
161 }
162 double v = 0.;
163 for(std::size_t i=0;i<w.size();++i) {
164 const std::string u = uuid2string(string2uuid(gc.getUUID(w[i])));
165 if(u == lineage)
166 continue; // the literal lineage: not summed
167 auto cit = co.find(u);
168 if(cit == co.end())
169 throw CircuitException("mobius: a gate_mobius child has no coefficient");
170 v += static_cast<double>(cit->second) * mobiusEvalRec(gc, w[i], memo);
171 }
172 // The true value is a probability; a small fp excursion is folded away,
173 // a larger one means a compiler bug -- warn (a free sanity check).
174 constexpr double tol = 1e-9;
175 if(v < -tol || v > 1.0 + tol)
176 provsql_warning("mobius: signed combination left [0,1] before clamping "
177 "(value %g) -- possible compiler bug", v);
178 if(v < 0.) v = 0.; else if(v > 1.) v = 1.;
179 r = v;
180 break;
181 }
182 default:
183 throw CircuitException("mobius: unsupported gate type in the Möbius-route "
184 "circuit");
185 }
186 memo[g] = r;
187 return r;
188}
189
190/// The literal-lineage child UUID of a gate_mobius-rooted @p token (the "L:"
191/// entry in extra), read from the RAW circuit -- the load-time simplifier may
192/// strip the gate_mobius extra, so a simplified read is unreliable. Empty if
193/// the token carries no lineage (a measure-only build).
194std::string mobiusLineageOf(pg_uuid_t token)
195{
196 const bool s1 = provsql_simplify_on_load;
197 const bool s2 = provsql_boolean_provenance;
198 const bool s3 = provsql_absorptive_provenance;
202 std::string lineage;
203 try {
205 const std::string ex = gc.getExtra(gc.getGate(uuid2string(token)));
206 const std::size_t p = ex.find("L:");
207 if(p != std::string::npos) {
208 const std::size_t e = ex.find(' ', p);
209 lineage = ex.substr(p + 2,
210 e == std::string::npos ? std::string::npos : e - p - 2);
211 }
212 } catch(...) { /* leave empty */ }
216 return lineage;
217}
218
219double mobiusProbabilityImpl(pg_uuid_t token)
220{
221 // Load the circuit RAW: the load-time simplifier (foldSemiringIdentities /
222 // foldBooleanIdentities) rewrites the gate_mobius children's gates, which
223 // would break the coefficient<->child association. The Möbius sweep needs
224 // the circuit exactly as the compiler built it.
225 const bool s1 = provsql_simplify_on_load;
226 const bool s2 = provsql_boolean_provenance;
227 const bool s3 = provsql_absorptive_provenance;
231 double r;
232 try {
234 gate_t root = gc.getGate(uuid2string(token));
235 std::map<gate_t,double> memo;
236 r = mobiusEvalRec(gc, root, memo);
237 } catch(...) {
241 throw;
242 }
246 return r;
247}
248
249
250/// Trim leading/trailing ASCII spaces and tabs.
251string trim_arg(const string &s)
252{
253 size_t a = s.find_first_not_of(" \t");
254 if(a == string::npos)
255 return string();
256 size_t b = s.find_last_not_of(" \t");
257 return s.substr(a, b - a + 1);
258}
259
260/**
261 * @brief Parsed probability-method argument string.
262 *
263 * @c kv holds the @c key=value pairs (key lower-cased, @c eps folded to
264 * @c epsilon); @c positional holds the comma-separated tokens that carry no
265 * @c '=' -- the bare-number (@c monte-carlo) and
266 * @c 'delta;epsilon' / @c 'tool;args' (@c weightmc / @c wmc) shortcuts.
267 */
268struct MethodArgs {
269 map<string, string> kv;
270 vector<string> positional;
271 bool has(const string &k) const { return kv.find(k) != kv.end(); }
272 string get(const string &k) const {
273 auto it = kv.find(k);
274 return it == kv.end() ? string() : it->second;
275 }
276};
277
278/**
279 * @brief Tokenise a probability-method argument string.
280 *
281 * The grammar is shared by every method: a comma-separated list whose
282 * @c key=value items populate @c MethodArgs::kv and whose bare items (no
283 * @c '=') go verbatim into @c MethodArgs::positional. None of these
284 * shortcuts use a comma, so each survives as a single positional token (a
285 * bare integer for @c monte-carlo, @c 'delta;epsilon' for @c weightmc,
286 * @c 'tool;args' for @c wmc), letting the canonical @c key=value form and the
287 * shorthand form coexist.
288 */
289MethodArgs parse_method_args(const string &args)
290{
291 MethodArgs out;
292 stringstream ss(args);
293 string tok;
294 while(getline(ss, tok, ',')) {
295 string t = trim_arg(tok);
296 if(t.empty())
297 continue;
298 auto eq = t.find('=');
299 if(eq == string::npos) {
300 out.positional.push_back(t);
301 } else {
302 string key = trim_arg(t.substr(0, eq));
303 string val = trim_arg(t.substr(eq + 1));
304 transform(key.begin(), key.end(), key.begin(),
305 [](unsigned char c){ return tolower(c); });
306 if(key == "eps")
307 key = "epsilon";
308 out.kv[key] = val;
309 }
310 }
311 return out;
312}
313
314/// Raise if any kv key lies outside @p allowed, naming the method.
315void reject_unknown_keys(const MethodArgs &a, const set<string> &allowed,
316 const char *method)
317{
318 for(const auto &p : a.kv)
319 if(allowed.find(p.first) == allowed.end())
320 provsql_error("method '%s': unknown argument key '%s'",
321 method, p.first.c_str());
322}
323
324/// Parse a non-negative integer that consumes the whole string.
325bool parse_ulong_full(const string &v, unsigned long &out)
326{
327 if(v.empty() || v.find_first_not_of("0123456789") != string::npos)
328 return false;
329 try {
330 size_t pos = 0;
331 out = stoul(v, &pos);
332 return pos == v.size();
333 } catch(const std::exception &) {
334 return false;
335 }
336}
337
338/// Parse a finite double that consumes the whole string.
339bool parse_double_full(const string &v, double &out)
340{
341 if(v.empty())
342 return false;
343 try {
344 size_t pos = 0;
345 out = stod(v, &pos);
346 return pos == v.size();
347 } catch(const std::exception &) {
348 return false;
349 }
350}
351
352/**
353 * @brief Validate and read @c epsilon / @c delta from the parsed args.
354 *
355 * Shared by every approximate method (@c monte-carlo, @c karp-luby,
356 * @c weightmc / @c wmc) so the keys, the @c eps alias, and the
357 * @c epsilon in (0,1] / @c delta in (0,1) range checks are uniform. @p eps and
358 * @p delta carry the caller's defaults on entry and are overwritten only when
359 * the corresponding key is present.
360 */
361void parse_eps_delta(const MethodArgs &a, const char *method,
362 double &eps, double &delta)
363{
364 if(a.has("epsilon") && (!parse_double_full(a.get("epsilon"), eps)
365 || eps <= 0. || eps > 1.))
366 provsql_error("method '%s': epsilon must be in (0, 1]", method);
367 if(a.has("delta") && (!parse_double_full(a.get("delta"), delta)
368 || delta < 0. || delta >= 1.))
369 provsql_error("method '%s': delta must be in [0, 1)", method);
370}
371
372/**
373 * @brief A resolved sampling request: a fixed count, or an @c (eps,delta) target.
374 *
375 * @c fixed selects @c samples; otherwise the caller turns @c (eps,delta) into a
376 * sample count with its own bound (additive for @c monte-carlo, relative for
377 * @c karp-luby).
378 */
379struct SampleSpec {
380 bool fixed = false;
381 unsigned long samples = 0;
382 double eps = 0.1, delta = 0.05;
383 bool has_max = false;
384 unsigned long max_samples = 0;
385};
386
387/**
388 * @brief Parse and validate the argument grammar shared by the sampling methods.
389 *
390 * The grammar is @c samples=N | a bare integer | @c
391 * epsilon=E[,delta=D][,max_samples=M]. This routine only resolves *which* path
392 * the user asked for and validates the keys / ranges; the @c (eps,delta) -> N
393 * conversion is method-specific and applied by the caller. An empty argument
394 * selects the adaptive path with the default @c (eps=0.1, delta=0.05).
395 */
396SampleSpec parse_sample_spec(const MethodArgs &a, const char *method)
397{
398 reject_unknown_keys(a, {"samples", "epsilon", "delta", "max_samples"}, method);
399
400 const bool has_samples = a.has("samples") || !a.positional.empty();
401 const bool has_adaptive = a.has("epsilon") || a.has("delta");
402
403 if(a.positional.size() > 1)
404 provsql_error("method '%s': too many positional arguments", method);
405 if(a.has("samples") && !a.positional.empty())
406 provsql_error("method '%s': give either samples= or a bare integer, "
407 "not both", method);
408 if(has_samples && has_adaptive)
409 provsql_error("method '%s': samples is mutually exclusive with "
410 "epsilon/delta", method);
411 if(a.has("max_samples") && !has_adaptive)
412 provsql_error("method '%s': max_samples applies only to the adaptive "
413 "epsilon/delta path", method);
414 if(a.has("delta") && !a.has("epsilon"))
415 provsql_error("method '%s': delta requires epsilon", method);
416
417 SampleSpec s;
418 if(has_samples) {
419 s.fixed = true;
420 const string v = a.has("samples") ? a.get("samples") : a.positional[0];
421 if(!parse_ulong_full(v, s.samples) || s.samples == 0)
422 provsql_error("method '%s': invalid sample count '%s'", method, v.c_str());
423 return s;
424 }
425
426 parse_eps_delta(a, method, s.eps, s.delta);
427 // delta == 0 is a DETERMINISTIC request: valid only on the tolerance paths
428 // ('relative'/'additive'), which route it to the d-tree / an exact method.
429 // A sampler invoked by name cannot honour it (infinite sample count).
430 if(s.delta == 0. && string(method) != "relative"
431 && string(method) != "additive")
432 provsql_error("method '%s': delta must be in (0, 1); delta = 0 "
433 "(deterministic) is supported only on the 'relative' / "
434 "'additive' paths, which route to the d-tree or an exact "
435 "method", method);
436 if(a.has("max_samples")) {
437 s.has_max = true;
438 if(!parse_ulong_full(a.get("max_samples"), s.max_samples) || s.max_samples == 0)
439 provsql_error("method '%s': invalid max_samples '%s'", method,
440 a.get("max_samples").c_str());
441 }
442 return s;
443}
444
445/// Clamp a real sample count into @c unsigned @c long, honouring @c max_samples.
446unsigned long finalize_adaptive(double nd, const SampleSpec &s)
447{
448 // Clamp only to stay within unsigned long; the count is otherwise honest,
449 // and max_samples / query cancel bound the runtime.
450 unsigned long n = (nd >= 9e18) ? static_cast<unsigned long>(9e18)
451 : static_cast<unsigned long>(nd);
452 if(n == 0)
453 n = 1;
454 if(s.has_max && n > s.max_samples)
455 n = s.max_samples;
456 return n;
457}
458
459/// Format a double compactly for the approximation-guarantee notice.
460string fmt_num(double x)
461{
462 char buf[32];
463 snprintf(buf, sizeof(buf), "%.6g", x);
464 return string(buf);
465}
466
467/**
468 * @brief Emit the machine-readable approximation-guarantee NOTICE (verbose>=5).
469 *
470 * An approximate method's estimate carries an @c (eps,delta) error guarantee;
471 * we surface it as a structured NOTICE that downstream UIs (Studio floors
472 * @c verbose_level at 5 for evaluation) parse and render. @p kind is
473 * @c "additive" (@c |est-p| <= eps) or @c "relative" (@c est within a
474 * @c 1±eps factor of @c p), each holding with probability @c >= 1-delta.
475 * Optional fields are omitted when not applicable: @p delta @c < 0,
476 * @p samples @c == 0, @p clauses @c < 0, @p tool empty. Gated on
477 * @c verbose_level>=5 so plain SQL evaluation (and the regression suite) stay
478 * quiet by default.
479 */
480void emit_guarantee(const char *kind, double eps, double delta,
481 unsigned long samples, long clauses, const char *tool)
482{
483 if(provsql_verbose < 5)
484 return;
485 string msg = "approximation-guarantee: kind=" + string(kind)
486 + " eps=" + fmt_num(eps);
487 if(delta >= 0.)
488 msg += " delta=" + fmt_num(delta);
489 if(samples > 0)
490 msg += " samples=" + std::to_string(samples);
491 if(clauses >= 0)
492 msg += " clauses=" + std::to_string(clauses);
493 if(tool && *tool)
494 msg += " tool=" + string(tool);
495 provsql_notice("%s", msg.c_str());
496}
497
498/// Whether a @c wmc tool is an approximate (multiplicative-guarantee) counter.
499bool is_approx_wmc_tool(const string &tool)
500{
501 return tool == "weightmc" || tool == "approxmc";
502}
503
504/// Extract weightmc's epsilon from a @c wmcCount opt string (@c "delta;epsilon").
505double eps_from_wmc_opt(const string &opt)
506{
507 auto semi = opt.find(';');
508 if(semi == string::npos)
509 return 0.8; // no epsilon field: wmcCount's own default tolerance
510 double e;
511 return (parse_double_full(opt.substr(semi + 1), e) && e > 0.) ? e : 0.8;
512}
513
514/**
515 * @brief Resolve the @c monte-carlo sample count from the parsed args.
516 *
517 * A fixed @c samples=N (or bare integer), or an *additive* @c (eps,delta)
518 * guarantee: the sample mean of the Bernoulli circuit indicator is within
519 * @c eps of the true probability with probability at least @c 1-delta after
520 * @c N = ceil(ln(2/delta) / (2*eps^2)) samples (Hoeffding's inequality, so the
521 * count is independent of the probability being estimated). This is an
522 * *absolute* error bound; @c karp-luby provides the *relative* one needed on
523 * rare-event outputs. Also emits the additive guarantee NOTICE.
524 */
525unsigned long monte_carlo_samples(const MethodArgs &a)
526{
527 SampleSpec s = parse_sample_spec(a, "monte-carlo");
528 unsigned long n = s.fixed
529 ? s.samples
530 : finalize_adaptive(ceil(log(2.0 / s.delta) / (2.0 * s.eps * s.eps)), s);
531 // For a fixed N, report the additive eps achieved at the conventional
532 // delta=0.05; for the adaptive path, report the requested (eps,delta).
533 const double eps = s.fixed
534 ? sqrt(log(2.0 / 0.05) / (2.0 * static_cast<double>(n))) : s.eps;
535 const double delta = s.fixed ? 0.05 : s.delta;
536 emit_guarantee("additive", eps, delta, n, -1, nullptr);
537 return n;
538}
539
540/**
541 * @brief Build the @c wmcCount opt string (@c "delta;epsilon") from the args.
542 *
543 * Canonical form @c epsilon=E[,delta=D], validated through the same
544 * @c parse_eps_delta as the sampling methods; the positional @c 'delta;epsilon'
545 * is accepted as a documented legacy alias (forwarded verbatim). @c wmcCount
546 * reads only @c epsilon (it drives the @c {pivotAC} approximation tolerance), so
547 * @c delta is carried for the legacy two-field order but is presently inert for
548 * the tool.
549 */
550string wmc_opt_from_args(const MethodArgs &a, const char *method)
551{
552 if(!a.positional.empty()) {
553 if(a.has("epsilon") || a.has("delta"))
554 provsql_error("method '%s': give either the legacy 'delta;epsilon' or "
555 "epsilon=/delta=, not both", method);
556 if(a.positional.size() > 1)
557 provsql_error("method '%s': too many positional arguments", method);
558 return a.positional[0];
559 }
560 reject_unknown_keys(a, {"epsilon", "delta"}, method);
561 // weightmc's own epsilon default (0.8) applies when epsilon is omitted, so
562 // validate but emit only the fields the user gave.
563 double eps = 0.8, delta = 0.5;
564 parse_eps_delta(a, method, eps, delta);
565 return (a.has("delta") ? a.get("delta") : string()) + ";"
566 + (a.has("epsilon") ? a.get("epsilon") : string());
567}
568
569/**
570 * @brief Run Karp-Luby on a DNF-shaped circuit and surface its guarantee.
571 *
572 * Two paths, selected by the shared argument grammar:
573 *
574 * - A fixed @c samples=N (or bare integer): the *stratified* fixed-budget
575 * estimator (@c BooleanCircuit::karpLuby). Reports the relative @c eps that
576 * @c N rounds deliver over @p m clauses at the conventional @c delta=0.05.
577 * - An adaptive @c (eps,delta) target (the default @c eps=0.1, @c delta=0.05):
578 * the Dagum-Karp-Luby-Ross self-adjusting *stopping rule*
579 * (@c BooleanCircuit::karpLubyStopping), which samples until the accept
580 * count reaches @c Y1 = 1+(1+eps)*4*(e-2)*ln(2/delta)/eps^2 and reports the
581 * exact @c (eps,delta) over the rounds actually run. The cap defaults to the
582 * fixed worst-case round count @c ceil(Y1*m) (so the adaptive run never costs
583 * more than ~(1+eps) times the old fixed bound) and is overridden by
584 * @c max_samples; hitting it before the target downgrades the guarantee to
585 * the relative @c eps achieved at the spent budget (with a warning).
586 *
587 * Unlike @c monte-carlo's additive bound, this controls the *relative* error,
588 * which is what stays meaningful on rare-event outputs.
589 */
590double evaluate_karp_luby(const BooleanCircuit &c,
591 const std::vector<gate_t> &clauses,
592 const std::vector<std::set<gate_t> > &supports,
593 const MethodArgs &a)
594{
595 const size_t m = clauses.size();
596 const double e = exp(1.0);
597 const double mm = (m == 0) ? 1. : static_cast<double>(m);
598 SampleSpec s = parse_sample_spec(a, "karp-luby");
599
600 if(s.fixed) {
601 double r = c.karpLuby(clauses, supports, s.samples);
602 const double eps =
603 sqrt(4.0 * (e - 2.0) * mm * log(2.0 / 0.05) / static_cast<double>(s.samples));
604 emit_guarantee("relative", eps, 0.05, s.samples, static_cast<long>(m), nullptr);
605 return r;
606 }
607
608 // Adaptive: the self-adjusting stopping rule, capped at ceil(Y1*m) by default.
609 const double Y = 4.0 * (e - 2.0) * log(2.0 / s.delta) / (s.eps * s.eps);
610 const double Y1 = 1.0 + (1.0 + s.eps) * Y;
611 const unsigned long cap =
612 s.has_max ? s.max_samples : finalize_adaptive(ceil(Y1 * mm), s);
613 unsigned long used = 0;
614 bool reached = false;
615 double r = c.karpLubyStopping(clauses, supports, s.eps, s.delta,
616 cap, used, reached);
617 if(reached || used == 0) {
618 emit_guarantee("relative", s.eps, s.delta, used, static_cast<long>(m), nullptr);
619 } else {
620 const double eps =
621 sqrt(4.0 * (e - 2.0) * mm * log(2.0 / 0.05) / static_cast<double>(used));
622 provsql_warning("method 'karp-luby': the stopping rule reached its "
623 "%lu-sample cap before the (epsilon=%g, delta=%g) target; "
624 "reporting the relative guarantee achieved at the samples "
625 "spent", cap, s.eps, s.delta);
626 emit_guarantee("relative", eps, 0.05, used, static_cast<long>(m), nullptr);
627 }
628 return r;
629}
630
631} // anonymous namespace
632
633/// External entry point for the Möbius-route probability sweep (declared in
634/// mobius_evaluate.h, used by the stats SRF in mobius_evaluate.cpp).
636{
637 return mobiusProbabilityImpl(token);
638}
639
640/**
641 * @brief Collect the inversion-free per-input order keys for the structured
642 * builder.
643 *
644 * Walks the @c GenericCircuit @p gc for @c K-prefixed annotation gates whose
645 * child is a @c gate_input (the per-input order markers attached by the planner
646 * on the certified path), parses each key, and maps the wrapped input to its
647 * @c BooleanCircuit variable via @p gc_to_bc. Returns @c true only if every
648 * @c BooleanCircuit input reachable from @p bc_root carries a key (the
649 * structured builder needs a total order over all variables); a missing marker
650 * means the certified markers are absent / incomplete and the caller must not
651 * use the structured path.
652 */
654 const GenericCircuit &gc, gate_t gc_root,
655 const std::unordered_map<gate_t, gate_t> &gc_to_bc,
656 const BooleanCircuit &c, gate_t bc_root,
657 std::map<gate_t, StructuredDNNFBuilder::InputKey> &out)
658{
659 std::set<gate_t> seen;
660 std::stack<gate_t> st;
661 st.push(gc_root);
662 while (!st.empty()) {
663 gate_t g = st.top(); st.pop();
664 if (!seen.insert(g).second) continue;
665 if (gc.getGateType(g) == gate_annotation) {
666 std::string ex = gc.getExtra(g); // must outlive the parse (k points into it)
667 SafeCertKey k;
668 if (safe_cert_key_parse(ex.c_str(), &k)) {
669 const auto &w = gc.getWires(g);
670 if (!w.empty() && gc.getGateType(w[0]) == gate_input) {
671 auto it = gc_to_bc.find(w[0]);
672 if (it != gc_to_bc.end())
673 out[it->second] = StructuredDNNFBuilder::InputKey{
674 std::string(k.root, k.root_len),
675 std::string(k.sec, k.sec_len), k.factor };
676 }
677 }
678 }
679 for (gate_t ch : gc.getWires(g)) st.push(ch);
680 }
681
682 /* every Boolean input must be ordered */
683 std::set<gate_t> bseen;
684 std::stack<gate_t> bst;
685 bst.push(bc_root);
686 while (!bst.empty()) {
687 gate_t g = bst.top(); bst.pop();
688 if (!bseen.insert(g).second) continue;
689 if (c.getGateType(g) == BooleanGate::IN) {
690 if (out.find(g) == out.end())
691 return false;
692 } else {
693 for (gate_t ch : c.getWires(g)) bst.push(ch);
694 }
695 }
696 return true;
697}
698
699/**
700 * @brief Flatten the per-input order keys into a total rank for the structured
701 * builder's order-only constructor.
702 *
703 * Sorts the certified inputs into a Prop. 4.5-consistent order -- root-class
704 * value first (one independent block per value), then secondary-class value
705 * (one tile per value within a block), then the shared self-join guard before
706 * the payloads of its tile, then by factor -- and assigns consecutive ranks.
707 * Ties (two inputs with identical keys) keep a deterministic order via the
708 * input gate id, so distinct variables always get distinct ranks. Unlike the
709 * keyed (factored-sweep) constructor this makes no single-secondary-axis /
710 * one-payload-per-tile assumption, so it certifies every hierarchical
711 * inversion-free lineage, including the self-join-free case.
712 */
713static std::map<gate_t, int> inversion_free_rank(
714 const std::map<gate_t, StructuredDNNFBuilder::InputKey> &keys)
715{
716 std::vector<std::pair<gate_t, StructuredDNNFBuilder::InputKey>> v(
717 keys.begin(), keys.end());
718 std::sort(v.begin(), v.end(), [](const auto &a, const auto &b) {
719 const auto &ka = a.second, &kb = b.second;
720 if (ka.root != kb.root) return ka.root < kb.root;
721 if (ka.sec != kb.sec) return ka.sec < kb.sec;
722 int ga = (ka.factor == StructuredDNNFBuilder::GUARD_FACTOR) ? 0 : 1;
723 int gb = (kb.factor == StructuredDNNFBuilder::GUARD_FACTOR) ? 0 : 1;
724 if (ga != gb) return ga < gb;
725 if (ka.factor != kb.factor) return ka.factor < kb.factor;
726 return a.first < b.first;
727 });
728 std::map<gate_t, int> rank;
729 int r = 0;
730 for (const auto &p : v) rank[p.first] = r++;
731 return rank;
732}
733
735{
736 // Compile a query certified inversion-free to its structured d-DNNF (the
737 // same artefact the 'inversion-free' probability method builds), so the KC
738 // surface can render / measure it. Mirrors the dispatch in
739 // probability_evaluate_internal: the per-input order keys live on the
740 // GenericCircuit's annotation markers, so we go through the generic circuit
741 // rather than getBooleanCircuit(token, ...) directly.
743 gate_t gc_root = gc.getGate(uuid2string(token));
744 std::string ex = gc.getExtra(gc_root);
745 if (ex.empty() || ex[0] != SAFE_CERT_EXTRA_PREFIX_RECIPE)
746 throw CircuitException("compile 'inversion-free': the provenance root "
747 "carries no inversion-free certificate");
748 gate_t root;
749 std::unordered_map<gate_t, gate_t> gc_to_bc;
750 BooleanCircuit c = getBooleanCircuit(gc, token, root, gc_to_bc);
751 std::map<gate_t, StructuredDNNFBuilder::InputKey> keys;
752 if (!collect_inversion_free_keys(gc, gc_root, gc_to_bc, c, root, keys))
753 throw CircuitException("compile 'inversion-free': the certificate's inputs "
754 "lack per-input order markers");
755 return StructuredDNNFBuilder(c, root, inversion_free_rank(keys)).dnnf();
756}
757
758// ---------------------------------------------------------------------------
759// Probability-method catalog (see ProbabilityMethod.h).
760//
761// Each dispatch branch is a ProbabilityMethod object: chooseAndRun runs the
762// cost-based chooser over the default-chain methods, and
763// byName runs each explicit method. The RV+monte-carlo special case and
764// every probability-side pre-pass stay in probability_evaluate_internal.
765// ---------------------------------------------------------------------------
766
767// Forward declaration: the whole-circuit (eps,delta)-relative stopping-rule
768// estimator (defined below probability_evaluate_internal) is delegated to by the
769// portfolio's StoppingRuleMethod, which is defined earlier (in the method-catalog
770// block). It operates on the GenericCircuit so it serves Boolean, RV and HAVING
771// circuits uniformly.
772static void run_stopping_rule(GenericCircuit &gc, gate_t gc_root,
773 const MethodArgs &a, double &result,
774 std::string &actual_method);
775
776namespace provsql {
777
778/// Thrown by a method that gave up under its budget but learned a tighter cost
779/// estimate: the chooser keeps the method, now priced by that estimate, rather
780/// than dropping it, since it may still be cheaper than what remains.
785
786/// Sanity bound on the reachable-input count for the auto-chosen 2^N
787/// possible-worlds enumeration: above it the method drops out of the portfolio
788/// so it is never *attempted* (its 2^N cost already deprioritises it, but this
789/// guards against a catastrophic last-resort attempt if every cheaper method
790/// failed). The by-name call ignores it (possibleWorlds itself refuses 64 or
791/// more reachable inputs).
792/// The actual small-N-vs-compile crossover is a cost comparison, not this bound.
793static const size_t kPossibleWorldsSanityMax = 30;
794
795/// Largest clause count for which the auto-chosen sieve (2^m inclusion-exclusion)
796/// is admitted (matches BooleanCircuit::sieve's internal cap). The by-name call
797/// is unaffected.
798static const size_t kSieveSanityMaxClauses = 24;
799
800// ---------------------------------------------------------------------------
801// Cost-function constants. Each method's / feature's estimatedCost models its
802// actual asymptotic complexity (see doc / the complexity table) times one of
803// these constants, calibrated as described below. Parameters (all O(1) on the
804// EvalContext):
805// S = circuit_size (gates), N = n_inputs, m = dnf_num_clauses_, w = tw_proxy_.
806// The chooser acquires a feature only when no ready method is cheaper, so the
807// per-gate constants set the order of its first steps:
808// C_dnfShape <= C_independent <= C_twProxy
809// The DNF-shape walk runs first, then a read-once circuit runs 'independent'
810// without paying for the treewidth proxy. possible-worlds undercuts
811// 'independent' up to N = 4 (3e-6 * 2^N < 5e-5). compilation, the subprocess
812// last resort, has the largest constant of the exact methods.
813// Calibrated on this machine so that the value of each cost function is roughly
814// the number of MILLISECONDS the work takes (order-of-magnitude only -- the goal
815// is to know whether a cost is ~1, ~100, ~1e6 ms, not a precise fit). See the
816// calibration instrumentation (provsql.verbose_level >= 50) and doc.
817static const double kCostIndependent = 5e-5; // O(S): ~5e-5 * S
818static const double kCostInversionFree = 5e-5; // O(S + N log N) (~ independent)
819static const double kCostPossibleWorlds = 3e-6; // O(S * 2^N): ~3e-6 * S*2^N
820static const double kCostSieve = 1e-5; // O(S * 2^m): ~1e-5 (rarely optimal)
821// NB: w is the degeneracy LOWER bound, so 2^w under-costs tree-decomposition when
822// the true treewidth exceeds it (a dense, low-degeneracy circuit can run far
823// slower than predicted). The constant is calibrated where the proxy is tight
824// (tree-like circuits, where tree-decomposition is the right pick anyway).
825static const double kCostTreeDecomp = 7e-4; // O(S * 2^w): ~7e-4 * S*2^w
826// compilation is an external knowledge compiler: a fixed subprocess startup
827// plus a compile that, while it exploits structure on easy shapes (~tens of ms
828// here), can struggle badly on others (the worst case is exponential). So we do
829// NOT model it as linear -- that is too optimistic; we use a pessimistic
830// super-linear S^1.5 above a startup floor, keeping it a strong last resort.
831static const double kCostCompilation = 2e-3; // ~2e-3 * S^1.5 ms ...
832static const double kCostCompilationFloor= 40.0; // ... but at least ~40 ms (startup + easy compile)
833// An external compiler picked by the chooser runs for at most
834// kCompilationBudgetFactor times the cost (in ms) of the next-best method, and
835// for at least kCompilationMinLimitMs, the time a compiler takes to start and
836// answer on an easy circuit, with some margin.
837static const double kCompilationBudgetFactor = 10.;
838static const double kCompilationMinLimitMs = 400.;
839static const double kCostDnfShapeFeature = 2e-6; // O(S): ~2e-6 * S
840static const double kCostTwProxyFeature = 3e-4; // O(S): ~3e-4 * S
841// Approximate portfolio members (relative & additive paths). Their cost has the
842// sample-budget term C = ln(2/delta)/eps^2 times per-sample O(S) work, but the
843// CONSTANT is PESSIMISTIC by design: measurement showed the runtimes depend on the
844// result probability p and the clause structure -- NOT static features (the same
845// lesson as the d-tree). karp-luby moved 14x (4 -> 52 ms on one DNF) purely with
846// p; the stopping rule's Dagum 1/p factor (it draws ~1/p worlds) took a rare-event
847// (p~0.06) circuit to 120-470 ms where a p~1 model predicts ~10. A single
848// constant cannot be accurate across p, so these are upper bounds. The chooser
849// then never UNDER-prices a sampler and picks a slow one: it prefers the
850// delta-independent d-tree (no 1/p, deterministic) and exact-when-cheaper, and
851// falls to a sampler only when it is the sole admissible option (non-DNF
852// relative / additive), where it is picked regardless of cost. Net ordering: a
853// cheap exact method (independent ~5e-5*S, a tiny-m sieve) underbids the
854// estimators so the path returns EXACT; a DNF approximation goes to the d-tree;
855// only a hard non-DNF approximation reaches the samplers.
856static const double kCostMonteCarlo = 1e-5; // additive: ~1e-5 * S * C (p-independent, the clean one)
857static const double kCostStoppingRule = 1e-3; // relative univ: ~1e-3 * S * C (pessimistic: covers the 1/p rare-event blow-up)
858static const double kCostKarpLuby = 3e-6; // relative DNF: ~3e-6 * S * m * C (pessimistic: covers the p-dependent slow case)
859static const double kCostDTreeExact = 3e-4; // d-tree exact: ~3e-4 * S * m (memoised Shannon; pessimistic vs tree-decomp on low tw)
860static const double kCostDTreeApprox = 4e-4; // d-tree approx: ~4e-4 * S / eps, DELTA-INDEPENDENT (deterministic -> overtakes samplers as delta shrinks)
861// d-tree's general (non-DNF) path computes the input footprint of every gate,
862// up to S * N set entries, which the per-node constants above leave out: ~1e-5
863// ms an entry on small circuits, rising to ~7e-5 where the sets no longer fit in
864// memory (measured: ~465M entries, 18.6 GB, in 32 s on a 5.3M-gate circuit of
865// 3,480 inputs).
866static const double kCostDTreeFootprint = 1e-5;
867// Speculative-execution budget conversion: ms per d-tree subproblem (recursion
868// entry). The chooser's budget is in ms (the next-best method's cost); the
869// d-tree counts subproblems, so budget_steps = budget_ms / (ms per subproblem).
870// The two recursions have different per-step cost (calibrated on the bench): the
871// monotone-DNF clause path pays an O(m^2) subsumption sweep per node (~1.4e-3
872// ms/step), the general circuit path only a footprint componentise + pivot scan
873// (~5e-4 ms/step). Using the right one keeps the budget honest -- a single
874// (smaller) constant under-charged the DNF path and let it run well past the
875// fallback's cost instead of bailing.
876// Recursions on cyclic data: the BoolExpr translation expands each cyclic
877// component of k rows into k-1 rounds over its terms (see solveFixSystem), about
878// 2 * (k-1) * terms gates, built at ~1.8e-4 ms a gate (measured on a grid of 900
879// rows and 3,480 terms). Past kMaxBooleanExpansion gates, the expansion does not
880// fit in memory and is refused; the samplers solve the system in each world
881// instead, at a per-world cost of the order of the circuit itself.
882static const double kCostBooleanExpansion = 1.8e-4;
883static const double kMaxBooleanExpansion = 1e8;
884static const double kCostDTreeMsPerStepDnf = 1.4e-3;
885static const double kCostDTreeMsPerStepGeneral = 5e-4;
886
887/// 2^k with the exponent clamped to keep the cost finite (a clamped exponent
888/// still sorts the method dead last -- it is then a guaranteed fall-through).
889static double pow2_clamped(size_t k)
890{
891 return std::ldexp(1.0, static_cast<int>(std::min<size_t>(k, 60)));
892}
893
894/// Per-evaluation circuit state threaded to a method's evaluate(). The Boolean
895/// view @c c is built once in probability_evaluate_internal; methods that need
896/// the multivalued rewrite trigger it (idempotently) through this context, so
897/// the rewrite fires exactly for the methods that need it.
899 // Generic-circuit state is needed only by the methods that consult the
900 // original circuit (inversion-free, stopping-rule); the d-D-construction
901 // portfolio (chooseAndBuildDD / makeDDAuto) works off the Boolean view alone,
902 // so these are pointers a Boolean-only caller can leave null.
908 std::unordered_map<gate_t, gate_t> *gc_to_bc;
910 const std::string &args;
911 bool explicitly_named; ///< invoked via byName (vs the default chain)
912 size_t n_inputs = 0; ///< input count N (O(1) cost feature)
913 size_t circuit_size = 0; ///< gate count S, the circuit-size parameter (O(1))
914 /// Speculative-execution budget: the estimated cost (in the chooser's ms-ish
915 /// units) of the next-cheapest admissible method. A budget-aware method
916 /// (the d-tree, tree-decomposition) stops once its own work would exceed this
917 /// and throws @c MethodRepricedException, so the chooser re-ranks it at a higher
918 /// cost and tries the next method -- keeping wasted work within a constant
919 /// factor of what the method finally spends. Infinity = no budget (the method is the last resort,
920 /// or budgeting is off).
921 double cost_budget = std::numeric_limits<double>::infinity();
922 /// Cost of an evaluation outside this Boolean view (sampling the equation
923 /// systems of a recursion directly): the chooser gives up, throwing, rather
924 /// than run a method or acquire a feature dearer than it. Infinity = none.
925 double outside_cost = std::numeric_limits<double>::infinity();
927 std::string actual_method;
928 bool linked_group = false;
929 bool fold_component = false;
930
933 c.rewriteMultivaluedGates();
935 }
936 }
937
938 // Cached DNF-shape feature: just (is-DNF, clause count) via the cheap
939 // dnfShapeInfo -- O(circuit), NO per-clause supports. The chooser ranks sieve
940 // from this; the supports (potentially O(m*N)) are built only if sieve /
941 // karp-luby actually runs, inside their evaluate().
942 mutable bool dnf_computed_ = false;
943 mutable bool dnf_ok_ = false;
944 mutable std::size_t dnf_num_clauses_ = 0;
945
946 void ensureDnfShape() const {
947 if(!dnf_computed_) {
948 dnf_ok_ = c.dnfShapeInfo(gate, dnf_num_clauses_);
949 dnf_computed_ = true;
950 }
951 }
952
953 // Cached treewidth proxy: a cheap degeneracy lower bound and the max degree
954 // (both from one O(V+E) pass; see TreeDecomposition::degeneracyLowerBound),
955 // computed once when the chooser is about to consider tree-decomposition.
956 mutable bool tw_computed_ = false;
957 mutable unsigned tw_proxy_ = 0;
958 /// Lower bound on the d-tree's cost, raised each time it overruns a budget.
959 double dtree_cost_floor_ = 0.;
960 /// Lower bound on tree-decomposition's cost, raised when the parts it
961 /// builds (islands, folded groups, residual) overrun a budget together.
963 /// Cost of the parts tree-decomposition has built in the current attempt.
964 double treedec_spent_ = 0.;
965 /// Lower bound on compilation's cost, raised when the external compiler
966 /// is stopped for running past its time limit.
968 /// Time, in ms, the external compiler has run in the current attempt.
970 mutable unsigned tw_max_degree_ = 0;
971
978
979 // --- Feature framework (see ProbabilityMethod.h) ---------------------------
980 // The chooser acquires non-free features lazily; these model their cost and
981 // perform the acquisition.
982
983 /// Heuristic acquisition cost of @p f, in the same work units as a method's
984 /// estimatedCost (so the chooser can compare "run this method" against
985 /// "acquire this feature").
986 double featureCost(Feature f) const {
987 switch(f) {
989 return kCostDnfShapeFeature * static_cast<double>(circuit_size); // O(S)
991 return kCostTwProxyFeature * static_cast<double>(circuit_size); // O(S)
992 }
993 return 0.;
994 }
995
996 bool hasFeature(Feature f) const {
997 switch(f) {
998 case Feature::DnfShape: return dnf_computed_;
1000 }
1001 return true;
1002 }
1003
1005 switch(f) {
1006 case Feature::DnfShape: ensureDnfShape(); break;
1008 }
1009 }
1010};
1011
1012namespace {
1013
1014/// The planner-time route that produced @p root's circuit, read back from the
1015/// route tag the route stamped there (see @c provsql_route). Three rewrites --
1016/// the safe-query read-once rewriter, the joint-width UCQ compiler and the
1017/// reachability compiler -- replace a query's ordinary lineage with a circuit
1018/// of their own, which they then hand to this dispatcher; the tag is what tells
1019/// them apart here, since all three are evaluated by the same
1020/// @c independentEvaluation sweep and would otherwise all report 'independent'.
1021///
1022/// Transparent @c gate_annotation wrappers (inversion-free certificate / order
1023/// keys) are skipped: they sit *above* the route's root. A tag is only read
1024/// off the route's own root gate -- a circuit that combines route output with
1025/// further provenance is no longer that route's circuit and reports as the
1026/// ordinary evaluation it is.
1027provsql_route rootRoute(const GenericCircuit *gc, gate_t root)
1028{
1029 if(gc == nullptr)
1030 return PROVSQL_ROUTE_NONE;
1031
1032 gate_t g = root;
1033 // Bounded walk: transparent annotation wrappers never nest deeply, and the
1034 // bound keeps a malformed circuit from looping here. A wrapper whose text
1035 // names a route ("route:<name>") is the route's own marker on the root it
1036 // produced (see wrapRoute in CertifiedDDMaterialize.cpp).
1037 for(unsigned i = 0; i < 8; ++i) {
1038 if(gc->getGateType(g) != gate_annotation || gc->getWires(g).size() != 1)
1039 break;
1040 const std::string text = gc->getExtra(g);
1041 if(text.rfind("route:", 0) == 0) {
1042 const std::string name = text.substr(6);
1045 if(name == provsql_route_name(r))
1046 return r;
1047 return PROVSQL_ROUTE_NONE;
1048 }
1049 g = gc->getWires(g)[0];
1050 }
1051
1052 // The tag on the gate itself: info1 of a route's gate_assumed wrapper, or,
1053 // for circuits stored before the route went on an annotation wrapper,
1054 // info2 of the materialised root (info1 being its d-D certificate).
1055 const auto [info1, info2] = gc->getInfos(g);
1056 const unsigned tag =
1057 gc->getGateType(g) == gate_assumed ? info1
1058 : (info1 == DNNF_CERT_INFO ? info2 : 0u);
1059
1060 switch(tag) {
1064 default: return PROVSQL_ROUTE_NONE;
1065 }
1066}
1067
1068/// Exact, linear sweep over a read-once circuit or certified d-D islands. Throws
1069/// on an input shared outside what the certificates license, which the chooser
1070/// catches to move on to the next method.
1071class IndependentMethod : public ProbabilityMethod {
1072public:
1073 std::string name() const override { return "independent"; }
1074 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1075 bool inDefaultChain() const override { return true; }
1076 // Interprets a mulinput (BID) block natively -- summing the mutually-exclusive
1077 // alternatives -- so it must see the raw circuit, not the Boolean rewrite.
1078 bool handlesMultivalued() const override { return true; }
1079 // O(S): one memoised linear pass over the circuit.
1080 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1081 return kCostIndependent * static_cast<double>(ctx.circuit_size);
1082 }
1083 // A route-tagged root is served by that route's own method (same sweep,
1084 // reported under the route's name), so the four stay mutually exclusive in
1085 // the chooser instead of racing on an identical cost. byName ignores this,
1086 // keeping explicit 'independent' available on any circuit as the escape
1087 // hatch that names the computation rather than its producer.
1088 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1089 return !ctx.linked_group
1090 && rootRoute(ctx.gc, ctx.gc_root) == PROVSQL_ROUTE_NONE;
1091 }
1092 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1093 double r = ctx.c.independentEvaluation(ctx.gate);
1094 ctx.actual_method = "independent";
1095 return r;
1096 }
1097};
1098
1099/**
1100 * @brief Shared base of the three planner-time route methods.
1101 *
1102 * Circuit production and evaluation are separate steps -- the route runs in the
1103 * planner, the evaluation here -- so the circuit itself is the channel between
1104 * them: the route stamps its tag on the root it produces (@c provsql_route) and
1105 * @c applicable() reads it back. This is the @c mobius / @c inversion-free
1106 * pattern: a first-class, by-name-invocable catalog method gated on a feature
1107 * of the provenance root.
1108 *
1109 * All three evaluate by @c independentEvaluation, which is not one algorithm
1110 * but two: a plain read-once sweep for the safe-query rewriter's circuit, and
1111 * the certified-island sweep (@c BooleanCircuit::evaluateCertifiedIsland, over
1112 * gates carrying @c DNNF_CERT_INFO) for the two compiled d-Ds. What the method
1113 * name adds over @c independent is which of the three produced the circuit.
1114 */
1115class RouteMethod : public ProbabilityMethod {
1116public:
1117 RouteMethod(provsql_route route, std::string name, std::string requirement)
1118 : route_(route), name_(std::move(name)),
1119 requirement_(std::move(requirement)) {}
1120
1121 std::string name() const override { return name_; }
1122 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1123 bool inDefaultChain() const override { return true; }
1124 // Same raw-circuit requirement as 'independent': a route's d-D can carry a
1125 // mulinput (BID) block the rewrite would dissolve.
1126 bool handlesMultivalued() const override { return true; }
1127 // O(S), exactly 'independent' -- it IS that sweep.
1128 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1129 return kCostIndependent * static_cast<double>(ctx.circuit_size);
1130 }
1131 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1132 return rootRoute(ctx.gc, ctx.gc_root) == route_;
1133 }
1134 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1135 // Named explicitly on an untagged root: report the missing precondition
1136 // rather than silently evaluating as something else (as 'mobius' and
1137 // 'inversion-free' do).
1138 if(ctx.explicitly_named && rootRoute(ctx.gc, ctx.gc_root) != route_)
1139 provsql_error("method '%s' requires %s", name_.c_str(),
1140 requirement_.c_str());
1141 double r = ctx.c.independentEvaluation(ctx.gate);
1142 ctx.actual_method = name_;
1143 return r;
1144 }
1145
1146private:
1147 const provsql_route route_;
1148 const std::string name_;
1149 const std::string requirement_;
1150};
1151
1152/// Exact, structured d-DNNF over an inversion-free certificate.
1153class InversionFreeMethod : public ProbabilityMethod {
1154public:
1155 std::string name() const override { return "inversion-free"; }
1156 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1157 bool inDefaultChain() const override { return true; }
1158 // O(S + N log N): linear structured-d-DNNF build + sorting the per-input keys.
1159 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1160 const double N = static_cast<double>(ctx.n_inputs);
1161 return kCostInversionFree
1162 * (static_cast<double>(ctx.circuit_size) + N * std::log2(N < 2 ? 2. : N));
1163 }
1164 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1165 // In the default chain: only when the certificate is present and the
1166 // kill-switch is on. byName ignores applicable() and enforces the explicit
1167 // rules (hard errors) in evaluate().
1168 return ctx.inv_free_cert && provsql_inversion_free;
1169 }
1170 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1171 if(ctx.explicitly_named && !ctx.inv_free_cert)
1172 provsql_error("method 'inversion-free' requires an inversion-free "
1173 "certificate on the provenance root (none is attached "
1174 "to the rows of a join that merges no rows and uses no "
1175 "relation twice: 'independent' applies to them)");
1176 std::map<gate_t, StructuredDNNFBuilder::InputKey> keys;
1177 if(!collect_inversion_free_keys(*ctx.gc, ctx.gc_root, *ctx.gc_to_bc, ctx.c,
1178 ctx.gate, keys)) {
1179 if(ctx.explicitly_named)
1180 provsql_error("method 'inversion-free': the provenance root carries a "
1181 "certificate but its inputs lack per-input order markers");
1182 // Chooser mode: fall through to the next method.
1183 throw CircuitException("inversion-free: inputs lack per-input order "
1184 "markers");
1185 }
1186 double r = StructuredDNNFBuilder(ctx.c, ctx.gate, inversion_free_rank(keys))
1187 .probability();
1188 ctx.actual_method = "inversion-free";
1189 return r;
1190 }
1191};
1192
1193/// The safe-UCQ Möbius-inversion route's evaluation method. Modelled on
1194/// 'inversion-free' -- a first-class, by-name-invocable catalog method in the
1195/// default chain, gated by a feature of the provenance root -- rather than a
1196/// terminal special-case. A @c gate_mobius root is a signed combination
1197/// @f$\sum_i c_i\,P(\text{child}_i)@f$ over certified-independent islands,
1198/// evaluated by a single linear sweep (@c mobiusProbabilityImpl). Because that
1199/// root is not a Boolean gate the circuit never becomes a @c BooleanCircuit, so
1200/// the dispatcher routes a @c gate_mobius-rooted token straight here (see
1201/// @c probability_evaluate_internal); @c applicable() also keeps it out of the
1202/// ordinary chain for Boolean circuits.
1203class MobiusMethod : public ProbabilityMethod {
1204public:
1205 std::string name() const override { return "mobius"; }
1206 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1207 bool inDefaultChain() const override { return true; }
1208 // Linear sweep over the certified-independent islands (the per-element
1209 // probabilities are read-once); same order as 'independent'.
1210 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1211 return kCostIndependent * static_cast<double>(ctx.circuit_size);
1212 }
1213 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1214 return ctx.gc != nullptr
1215 && ctx.gc->getGateType(ctx.gc_root) == gate_mobius;
1216 }
1217 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1218 if(ctx.gc == nullptr || ctx.gc->getGateType(ctx.gc_root) != gate_mobius)
1219 provsql_error("method 'mobius' requires a Möbius-route token (a "
1220 "gate_mobius signed-combination root)");
1221 ctx.actual_method = "mobius";
1222 return mobiusProbabilityImpl(ctx.token);
1223 }
1224};
1225
1226/// Whether a provsql.prob_cache / provsql.idp_fold setting applies to this
1227/// evaluation: 'auto' covers the methods ProvSQL chooses, so that a method
1228/// called by name runs as named; 'on' covers that call too.
1229static bool evalOptActive(int setting, const EvalContext &ctx)
1230{
1231 return setting == PROVSQL_EVAL_OPT_ON
1232 || (setting == PROVSQL_EVAL_OPT_AUTO && !ctx.explicitly_named);
1233}
1234
1235/// Shared evaluate() of the d-DNNF-producing methods: build through the fold
1236/// and the cache where they apply, and report what actually ran. @p builder
1237/// names the method as its cache entries record it; a call by name is answered
1238/// only from an entry of that builder.
1239template<typename BuildOn>
1240static double evaluateViaDD(EvalContext &ctx, const std::string &builder,
1241 BuildOn buildOn)
1242{
1243 const bool cache = evalOptActive(provsql_prob_cache, ctx);
1244 const bool fold = evalOptActive(provsql_idp_fold, ctx) && !ctx.fold_component;
1245 if(!(cache || fold) || !probCacheEligible(ctx.c, ctx.gate))
1246 return buildOn(ctx.c, ctx.gate, ctx).probabilityEvaluation();
1247
1248 ProbCacheReport report;
1249 ProbCacheOptions options;
1250 options.use_cache = cache;
1251 options.fold = fold;
1252 if(ctx.explicitly_named)
1253 options.required_builder = builder;
1254 options.last_builder = [&ctx]() { return ctx.actual_method; };
1255 options.report = &report;
1256 const double p = probCachedProbability(
1257 ctx.c, ctx.gate,
1258 [&](const BooleanCircuit &cc, gate_t g) { return buildOn(cc, g, ctx); },
1259 nullptr, options);
1260 ctx.actual_method = report.describe();
1261 return p;
1262}
1263
1264// makeDD's internal interpret-as-dd -> tree-decomposition -> compiler ladder is
1265// lifted here into three first-class catalog members, so the chooser can see
1266// and rank the three most cost-divergent exact compilers (linear / treewidth-
1267// bounded / external subprocess) instead of one opaque "compilation" blob, and
1268// last_eval_method reports the route actually taken. makeDD / makeDDByName stay
1269// for their dD-artifact callers (shapley, compile_to_ddnnf, ddnnf_stats).
1270
1271/// Exact, interpret the circuit directly as a d-DNNF and read off the
1272/// probability. By-name only -- deliberately NOT in the default chain: for a
1273/// probability *number* this is redundant with (indeed strictly weaker than)
1274/// 'independent'. interpretAsDD treats OR as independent-OR (De Morgan over a
1275/// decomposable AND), AND as a product, and throws "Not an independent circuit"
1276/// on a shared input -- exactly independentEvaluation's computation -- while
1277/// also rejecting the multivalued inputs and 0/1 constants that 'independent'
1278/// accepts. 'independent' performs the same computation at the same cost, so this
1279/// would be dead in the chain. Kept as an explicit method for parity with the
1280/// dD-artifact surfaces / debugging.
1281class InterpretAsDdMethod : public ProbabilityMethod {
1282public:
1283 std::string name() const override { return "interpret-as-dd"; }
1284 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1285 bool producesDD() const override { return true; }
1286 // O(S), the same cost as 'independent' -- for a probability *number* this IS
1287 // independentEvaluation (interpretAsDD treats OR as independent-OR, AND as a
1288 // product, throws on a shared input), which is why it stays out of the
1289 // probability default chain. In the d-D portfolio it is the cheapest route
1290 // and the artifact-producing twin of 'independent' (which yields no d-DNNF),
1291 // so it must carry this cost to be ranked first by chooseAndBuildDD.
1292 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1293 return kCostIndependent * static_cast<double>(ctx.circuit_size);
1294 }
1295 dDNNF buildDD(EvalContext &ctx) const override {
1296 dDNNF dd = ctx.c.interpretAsDD(ctx.gate);
1297 ctx.actual_method = "interpret-as-dd";
1298 return dd;
1299 }
1300 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1301 return buildDD(ctx).probabilityEvaluation();
1302 }
1303};
1304
1305/// Exact d-DNNF via min-fill tree decomposition. Default-chain member (after
1306/// inversion-free) and by-name "tree-decomposition". Throws above the treewidth
1307/// bound: in the chain that falls through to compilation; an explicit call
1308/// errors with the treewidth message (mirroring makeDD).
1309class TreeDecompositionMethod : public ProbabilityMethod {
1310public:
1311 std::string name() const override { return "tree-decomposition"; }
1312 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1313 bool inDefaultChain() const override { return true; }
1314 bool producesDD() const override { return true; }
1315 // Cost/applicability are gated by a cheap degeneracy lower bound on the
1316 // treewidth: if it already exceeds the build's MAX_TREEWIDTH, the bounded
1317 // min-fill build would certainly fail, so the method is ruled out (skipped
1318 // before the costly attempt). Otherwise the d-DNNF cost is exponential in the
1319 // treewidth; tw_proxy_ is a lower bound, so 2^tw_proxy * n is an optimistic
1320 // lower bound on the real cost (the build can still fail if the true treewidth
1321 // turns out above the bound -- the implicit half of the feature).
1322 std::vector<Feature> requiredFeatures() const override {
1323 return {Feature::TreewidthProxy};
1324 }
1325 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1326 return ctx.tw_proxy_ <= static_cast<unsigned>(TreeDecomposition::MAX_TREEWIDTH);
1327 }
1328 // O(S * 2^w): the d-DNNF is exponential in the treewidth (lower-bounded by the
1329 // degeneracy proxy w), and the min-fill build is poly and bounded by the S
1330 // factor. NB an earlier model multiplied in the max degree Delta^2 to charge
1331 // the build's per-step fill-in -- but for a DNF the root OR's fan-in IS the
1332 // clause count, so Delta^2 exploded (a 300-clause DNF -> Delta=300 -> cost
1333 // ~90000x too high) and the chooser fled a 7 ms tree-decomposition for a
1334 // 1900 ms compilation. The build is fast even at high fan-in (measured), so
1335 // Delta is dropped; 2^w (capped at the MAX_TREEWIDTH applicability bound) is
1336 // the real cost driver.
1337 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1338 return std::max(ctx.treedec_cost_floor_,
1339 kCostTreeDecomp * static_cast<double>(ctx.circuit_size)
1340 * pow2_clamped(ctx.tw_proxy_));
1341 }
1342 /// Thrown by buildOn when a part of the circuit has no tree decomposition
1343 /// of width MAX_TREEWIDTH that min-fill can find.
1344 struct PartOutOfReach {};
1345
1346 /// Builds the d-DNNF of @p cc below @p g: the circuit of @p ctx, or one
1347 /// of the parts it is evaluated in (an island, a folded group, the
1348 /// residual). The parts of one attempt share the budget of @p ctx, each
1349 /// being charged to @c treedec_spent_.
1350 static dDNNF buildOn(const BooleanCircuit &cc, gate_t g, EvalContext &ctx) {
1351 const bool whole = &cc == &ctx.c;
1352 // On the chooser's path, the cost is bounded by the next-best method's.
1353 // A by-name call keeps the full MAX_TREEWIDTH bound.
1354 const bool budgeted = !ctx.explicitly_named && std::isfinite(ctx.cost_budget);
1355 const double size = whole ? static_cast<double>(ctx.circuit_size)
1356 : static_cast<double>(cc.getNbGates());
1357 const double remaining = ctx.cost_budget - ctx.treedec_spent_;
1358 unsigned width_cap = TreeDecomposition::MAX_TREEWIDTH;
1359 try {
1360 // Stop the min-fill build as soon as a bag shows the width it would
1361 // take to exceed what is left of the budget (the degeneracy proxy that
1362 // priced the method is only a lower bound, and the build of a large
1363 // circuit is slow).
1364 if(budgeted) {
1365 const double ratio = remaining / (kCostTreeDecomp * size);
1366 const double w = ratio >= 1. ? std::floor(std::log2(ratio)) : 0.;
1367 width_cap = static_cast<unsigned>(
1368 std::min<double>(w, TreeDecomposition::MAX_TREEWIDTH));
1369 }
1370 TreeDecomposition td(cc, width_cap);
1371 // Speculative execution: the (poly) min-fill build has now discovered the
1372 // EXACT treewidth, where the cost estimate above used only the degeneracy
1373 // LOWER bound (which under-costs). Before paying the exponential d-DNNF
1374 // build, recompute the real cost from the discovered width; if it exceeds
1375 // what is left of the budget, bail so the chooser re-ranks the method at
1376 // the cost now known -- the build's own MAX_TREEWIDTH cap is the hard
1377 // ceiling, this is the competitive refinement.
1378 const double real_cost = kCostTreeDecomp * size
1379 * pow2_clamped(td.getTreewidth());
1380 if(budgeted && real_cost > remaining) {
1381 if(whole)
1382 ctx.tw_proxy_ = std::max(ctx.tw_proxy_,
1383 static_cast<unsigned>(td.getTreewidth()));
1384 reprice(ctx, real_cost,
1385 "tree-decomposition: discovered treewidth exceeds the budget");
1386 }
1387 dDNNF dd = dDNNFTreeDecompositionBuilder{cc, g, td}.build();
1388 ctx.treedec_spent_ += real_cost;
1389 ctx.actual_method = "tree-decomposition";
1390 return dd;
1391 } catch(TreeDecompositionException &) {
1392 if(ctx.explicitly_named && whole)
1393 provsql_error("Treewidth greater than %u",
1395 if(ctx.explicitly_named)
1396 throw PartOutOfReach();
1397 if(whole) {
1398 // The build needs a width above the cap, which raises the bound that
1399 // prices the method. It competes again at that price, and drops out
1400 // of the portfolio through applicable() once above MAX_TREEWIDTH.
1401 ctx.tw_proxy_ = std::max(ctx.tw_proxy_, width_cap + 1);
1402 throw MethodRepricedException(
1403 "tree-decomposition: treewidth above the bound");
1404 }
1405 // No decomposition of width MAX_TREEWIDTH was found for this part.
1406 // That does not rule the method out: min-fill is a heuristic, and may
1407 // do better on the whole circuit than on one of its parts.
1408 if(width_cap >= static_cast<unsigned>(TreeDecomposition::MAX_TREEWIDTH))
1409 throw PartOutOfReach();
1410 reprice(ctx, kCostTreeDecomp * size * pow2_clamped(width_cap + 1),
1411 "tree-decomposition: treewidth above the bound");
1412 }
1413 }
1414 /// Leaves the attempt for the chooser to rank the method again, at the
1415 /// cost now known: what the parts built so far took, plus @p part_cost
1416 /// for the one that does not fit. That is above the budget, hence above
1417 /// the estimate the method was picked on, so each retry raises the floor
1418 /// and this terminates.
1419 [[noreturn]] static void reprice(EvalContext &ctx, double part_cost,
1420 const char *why) {
1421 ctx.treedec_cost_floor_ =
1422 std::max(ctx.treedec_cost_floor_, ctx.treedec_spent_ + part_cost);
1423 throw MethodRepricedException(why);
1424 }
1425 dDNNF buildDD(EvalContext &ctx) const override {
1426 ctx.treedec_spent_ = 0.;
1427 return buildOn(ctx.c, ctx.gate, ctx);
1428 }
1429 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1430 ctx.treedec_spent_ = 0.;
1431 try {
1432 return evaluateViaDD(ctx, "tree-decomposition", buildOn);
1433 } catch(PartOutOfReach &) {
1434 // Splitting the circuit into islands or folded groups left a part
1435 // the method cannot build. Build the circuit whole, as is done when
1436 // neither the cache nor the fold applies: what the parts already
1437 // took stays charged to the budget.
1438 return buildOn(ctx.c, ctx.gate, ctx).probabilityEvaluation();
1439 }
1440 }
1441};
1442
1443/// Exact d-DNNF via an external knowledge compiler (d4 / c2d / minic2d / dsharp,
1444/// or a KCMCP server). Default-chain terminal (after tree-decomposition) and
1445/// by-name "compilation". An empty compiler argument auto-selects the
1446/// highest-preference available compiler (provsql.fallback_compiler / registry);
1447/// a non-empty @c args names the compiler and its options.
1448class CompilationMethod : public ProbabilityMethod {
1449public:
1450 std::string name() const override { return "compilation"; }
1451 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1452 bool inDefaultChain() const override { return true; }
1453 bool producesDD() const override { return true; }
1454 // Subprocess: a fixed startup plus a compile that exploits structure on easy
1455 // shapes but can struggle badly on others. Modelled as the pessimistic
1456 // max(startup_floor, slope * S^1.5) ms of kCostCompilation, so that on a large
1457 // circuit an approximation's bounded cost undercuts it. (It is the last
1458 // resort: cheaper in-process methods, when they apply, undercut it; when none
1459 // does, it is the only candidate and runs regardless.)
1460 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1461 const double s = static_cast<double>(ctx.circuit_size);
1462 return std::max(ctx.compilation_cost_floor_,
1463 std::max(kCostCompilationFloor,
1464 kCostCompilation * s * std::sqrt(s)));
1465 }
1466 static dDNNF buildOn(const BooleanCircuit &cc, gate_t g, EvalContext &ctx) {
1467 // On a chooser path (exact / relative / additive) ctx.args carries the
1468 // path's TOLERANCE string (epsilon=...,delta=...), not a compiler name, so
1469 // auto-select the compiler. Only a by-name 'compilation' call passes an
1470 // explicit compiler in ctx.args. (Without this, a relative/additive request
1471 // makes compilation try to use "epsilon=...,delta=..." as a compiler name,
1472 // which throws -- silently dropping compilation from the chooser and sending
1473 // the request to a worse method.)
1474 const std::string compiler =
1475 ctx.explicitly_named ? ctx.args : std::string();
1476 std::string used;
1477 // On the chooser's path, the compiler is held to the cost of the
1478 // next-best method: unlike the in-process methods it cannot tell that
1479 // it is overrunning, so it is stopped from outside, after
1480 // kCompilationBudgetFactor times that cost in ms (the same margin as the
1481 // d-tree's, for the cost being an estimate of the time, not the time),
1482 // and repriced at the time it is now known to exceed. The parts of one
1483 // attempt (islands, folded groups, residual) share the limit. A by-name
1484 // call, or compilation as the last method standing, has no limit.
1485 const bool budgeted = !ctx.explicitly_named && std::isfinite(ctx.cost_budget);
1486 const double limit_ms =
1487 std::max(kCompilationMinLimitMs,
1488 kCompilationBudgetFactor * ctx.cost_budget);
1489 const auto reprice = [&](const char *why) {
1490 ctx.compilation_cost_floor_ =
1491 std::max(ctx.compilation_cost_floor_, limit_ms);
1492 throw MethodRepricedException(why);
1493 };
1494 if(budgeted && ctx.compilation_spent_ms_ >= limit_ms)
1495 reprice("compilation: time limit reached");
1496 const auto t0 = std::chrono::steady_clock::now();
1497 dDNNF dd;
1498 try {
1499 ExternalToolTimeLimit limit(
1500 budgeted ? limit_ms - ctx.compilation_spent_ms_ : 0.);
1501 dd = cc.compilation(g, compiler, &used);
1502 } catch(ExternalToolTimeout &e) {
1503 reprice(e.what());
1504 }
1505 ctx.compilation_spent_ms_ += std::chrono::duration<double, std::milli>(
1506 std::chrono::steady_clock::now() - t0).count();
1507 // Report WHICH compiler ran (e.g. "compilation:d4"), not just "compilation":
1508 // on a chooser path the tool is auto-selected, so the bare label hid it.
1509 ctx.actual_method = used.empty() ? "compilation" : "compilation:" + used;
1510 return dd;
1511 }
1512 dDNNF buildDD(EvalContext &ctx) const override {
1513 ctx.compilation_spent_ms_ = 0.;
1514 return buildOn(ctx.c, ctx.gate, ctx);
1515 }
1516 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1517 ctx.compilation_spent_ms_ = 0.;
1518 // A call by name is answered from the cache only by the compiler it
1519 // names (resolved here, which also rejects an unknown one up front).
1520 std::string builder = "compilation";
1521 if(ctx.explicitly_named)
1522 builder += ":" + BooleanCircuit::checkCompiler(ctx.args);
1523 return evaluateViaDD(ctx, builder, buildOn);
1524 }
1525};
1526
1527/// Exact, naive 2^N enumeration. In the default chain for small circuits only
1528/// (cheap exact, preferred over tree-decomposition / compilation when N is
1529/// small); always available by name.
1530class PossibleWorldsMethod : public ProbabilityMethod {
1531public:
1532 std::string name() const override { return "possible-worlds"; }
1533 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1534 bool inDefaultChain() const override { return true; }
1535 // O(S * 2^N): enumerate 2^N worlds, evaluate the circuit (O(S)) in each.
1536 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1537 return kCostPossibleWorlds * static_cast<double>(ctx.circuit_size)
1538 * pow2_clamped(ctx.n_inputs);
1539 }
1540 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1541 return ctx.n_inputs > 0 && ctx.n_inputs <= kPossibleWorldsSanityMax;
1542 }
1543 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1544 // Only flag ignored args for an EXPLICIT `possible-worlds` request; when the
1545 // chooser auto-picks it on a relative/additive path, the args carry the path's
1546 // (eps,delta) tolerance, which an exact method legitimately ignores.
1547 if(ctx.explicitly_named && !ctx.args.empty())
1548 provsql_warning("Argument '%s' ignored for method possible-worlds",
1549 ctx.args.c_str());
1550 double r = ctx.c.possibleWorlds(ctx.gate);
1551 ctx.actual_method = "possible-worlds";
1552 return r;
1553 }
1554};
1555
1556/// Additive Monte Carlo (the non-RV path; the RV path is handled directly on
1557/// the GenericCircuit in probability_evaluate_internal before the catalog).
1558class MonteCarloMethod : public ProbabilityMethod {
1559public:
1560 std::string name() const override { return "monte-carlo"; }
1561 ToleranceKind guaranteeKind() const override { return ToleranceKind::Additive; }
1562 // Additive portfolio member: the universal fixed-sample estimator on the Boolean
1563 // view, serving the 'additive' path (and any-name).
1564 bool inDefaultChain() const override { return true; }
1565 bool isDeterministic() const override { return false; } // (eps,delta) sampler
1566 // O(S / eps^2 * ln(1/delta)) -- Hoeffding, p-independent.
1567 double estimatedCost(const EvalContext &ctx, const Tolerance &tol) const override {
1568 if(tol.epsilon <= 0.) return std::numeric_limits<double>::infinity();
1569 return kCostMonteCarlo * static_cast<double>(ctx.circuit_size)
1570 * std::log(2.0 / tol.delta)
1571 / (tol.epsilon * tol.epsilon);
1572 }
1573 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1574 unsigned long samples = monte_carlo_samples(parse_method_args(ctx.args));
1575 double r = ctx.c.monteCarlo(ctx.gate, static_cast<unsigned>(samples));
1576 ctx.actual_method = "monte-carlo";
1577 return r;
1578 }
1579};
1580
1581/// Karp-Luby FPRAS over a DNF-shaped monotone circuit. Relative portfolio member
1582/// (chosen on DNFs the cheap exact methods do not resolve) and by-name; runs before
1583/// the multivalued rewrite (it rejects multivalued inputs anyway).
1584class KarpLubyMethod : public ProbabilityMethod {
1585public:
1586 std::string name() const override { return "karp-luby"; }
1587 ToleranceKind guaranteeKind() const override { return ToleranceKind::Relative; }
1588 bool inDefaultChain() const override { return true; }
1589 bool isDeterministic() const override { return false; } // (eps,delta) sampler
1590 // Cost / applicability need the DNF-shape feature; the chooser acquires it
1591 // before calling them.
1592 std::vector<Feature> requiredFeatures() const override {
1593 return {Feature::DnfShape};
1594 }
1595 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1596 return ctx.dnf_ok_;
1597 }
1598 // O(S*m / eps^2 * ln(1/delta)) -- relative, p-independent (the m clauses
1599 // replace the 1/p of plain MC).
1600 double estimatedCost(const EvalContext &ctx, const Tolerance &tol) const override {
1601 if(tol.epsilon <= 0.) return std::numeric_limits<double>::infinity();
1602 const double m = static_cast<double>(ctx.dnf_num_clauses_ > 0
1603 ? ctx.dnf_num_clauses_ : 1);
1604 return kCostKarpLuby * static_cast<double>(ctx.circuit_size) * m
1605 * std::log(2.0 / tol.delta)
1606 / (tol.epsilon * tol.epsilon);
1607 }
1608 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1609 std::vector<gate_t> clauses;
1610 std::vector<std::set<gate_t> > supports;
1611 if(!ctx.c.dnfShape(ctx.gate, clauses, supports)) {
1612 provsql_warning("method 'karp-luby' applies only to a DNF-shaped circuit "
1613 "(a monotone OR-of-ANDs over input leaves); negation, "
1614 "comparison, aggregation, random-variable and "
1615 "multivalued-input gates are not supported");
1616 provsql_error("method 'karp-luby' requires a DNF-shaped provenance "
1617 "circuit");
1618 }
1619 double r = evaluate_karp_luby(ctx.c, clauses, supports,
1620 parse_method_args(ctx.args));
1621 ctx.actual_method = "karp-luby";
1622 return r;
1623 }
1624};
1625
1626/// Whole-circuit (eps,delta)-RELATIVE estimate via the Dagum-Karp-Luby-Ross stopping
1627/// rule -- the universal relative fallback (plain Boolean / RV / HAVING agg alike).
1628/// Relative portfolio member and by-name ('stopping-rule'). Operates on the
1629/// GenericCircuit (ctx.gc / ctx.gc_root), so it applies to every circuit regardless
1630/// of whether the Boolean view built; delegates to run_stopping_rule for the
1631/// max_samples cap, the relative->additive degradation, and the guarantee NOTICE.
1632class StoppingRuleMethod : public ProbabilityMethod {
1633public:
1634 std::string name() const override { return "stopping-rule"; }
1635 ToleranceKind guaranteeKind() const override { return ToleranceKind::Relative; }
1636 bool inDefaultChain() const override { return true; }
1637 bool isDeterministic() const override { return false; } // (eps,delta) sampler
1638 // O(S / (p*eps^2) * ln(1/delta)); p is not a static feature, modelled
1639 // optimistically at p ~ 1 (see the kCost block). Above karp-luby on DNFs and
1640 // above plain MC, but below the cheap exact methods so "exact when cheaper" wins.
1641 double estimatedCost(const EvalContext &ctx, const Tolerance &tol) const override {
1642 if(tol.epsilon <= 0.) return std::numeric_limits<double>::infinity();
1643 return kCostStoppingRule * static_cast<double>(ctx.circuit_size)
1644 * std::log(2.0 / tol.delta)
1645 / (tol.epsilon * tol.epsilon);
1646 }
1647 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1648 double r = 0.;
1649 run_stopping_rule(*ctx.gc, ctx.gc_root, parse_method_args(ctx.args), r,
1650 ctx.actual_method);
1651 return r;
1652 }
1653};
1654
1655/// Exact inclusion-exclusion over a monotone DNF. Portfolio member (runs before
1656/// the multivalued rewrite, like karp-luby; dnfShape rejects multivalued inputs)
1657/// and by-name. Work-weighted cost N*2^m in the clause count m: the chooser
1658/// picks it over possible-worlds when there are fewer clauses than inputs
1659/// (m < N), and over the compilers when m is small -- yet it stays behind
1660/// linear-exact 'independent' on a read-once DNF.
1661class SieveMethod : public ProbabilityMethod {
1662public:
1663 std::string name() const override { return "sieve"; }
1664 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1665 bool inDefaultChain() const override { return true; }
1666 // Cost / applicability need the DNF-shape feature; the chooser acquires it
1667 // before calling them.
1668 std::vector<Feature> requiredFeatures() const override {
1669 return {Feature::DnfShape};
1670 }
1671 bool applicable(const EvalContext &ctx, const Tolerance &) const override {
1672 return ctx.dnf_ok_ && ctx.dnf_num_clauses_ <= kSieveSanityMaxClauses;
1673 }
1674 // O(S * 2^m): inclusion-exclusion over 2^m clause subsets, each a product over
1675 // the union of supports (bounded by the circuit).
1676 double estimatedCost(const EvalContext &ctx, const Tolerance &) const override {
1677 if(!ctx.dnf_ok_)
1678 return std::numeric_limits<double>::infinity();
1679 return kCostSieve * static_cast<double>(ctx.circuit_size)
1680 * pow2_clamped(ctx.dnf_num_clauses_);
1681 }
1682 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1683 // Auto-chosen on a relative/additive path, the args are the path's (eps,delta)
1684 // tolerance, legitimately ignored by an exact method -- only warn when sieve was
1685 // requested explicitly.
1686 if(ctx.explicitly_named && !ctx.args.empty())
1687 provsql_warning("Argument '%s' ignored for method sieve",
1688 ctx.args.c_str());
1689 // Build the full clauses + supports now (only paid because sieve was
1690 // chosen); the cheap feature only validated the shape and counted clauses.
1691 std::vector<gate_t> clauses;
1692 std::vector<std::set<gate_t> > supports;
1693 if(!ctx.c.dnfShape(ctx.gate, clauses, supports)) {
1694 provsql_warning("method 'sieve' applies only to a DNF-shaped circuit "
1695 "(a monotone OR-of-ANDs over input leaves); negation, "
1696 "comparison, aggregation, random-variable and "
1697 "multivalued-input gates are not supported");
1698 provsql_error("method 'sieve' requires a DNF-shaped provenance circuit");
1699 }
1700 double r = ctx.c.sieve(clauses, supports);
1701 ctx.actual_method = "sieve";
1702 return r;
1703 }
1704};
1705
1706/// d-tree: deterministic anytime interval bounds for a Boolean circuit (Olteanu-
1707/// Huang), with an optimised path for a monotone DNF. Refines the cheap leaf
1708/// bound by independent-or decomposition and Shannon expansion until the tolerance
1709/// is met (exact when run to a zero-width interval), returning a certified
1710/// interval -- no failure probability. In the default chain on every path, and
1711/// selectable by name.
1712class DTreeBoundsMethod : public ProbabilityMethod {
1713public:
1714 std::string name() const override { return "d-tree"; }
1715 ToleranceKind guaranteeKind() const override { return ToleranceKind::Exact; }
1716 bool inDefaultChain() const override { return true; }
1717 // isDeterministic() defaults to true: the certified interval carries no
1718 // failure probability. That is the d-tree's reason for being in the chain --
1719 // it is the ONLY non-exact method admissible for a delta == 0 request, and its
1720 // cost is delta-INDEPENDENT, so it overtakes the (eps,delta) samplers as delta
1721 // shrinks. On low treewidth the exact compilers still win on cost; the d-tree
1722 // is auto-selected for deterministic / low-delta approximation and for exact
1723 // where the treewidth exceeds tree-decomposition's cap.
1724 std::vector<Feature> requiredFeatures() const override {
1725 // DnfShape selects the optimised monotone-DNF clause path and supplies the
1726 // clause count for the exact cost; a non-DNF circuit uses the general
1727 // circuit recursion (dtreeBoundsCircuit), so the method is applicable either
1728 // way -- the feature is a hint, not a gate.
1729 return {Feature::DnfShape};
1730 }
1731 bool applicable(const EvalContext &, const Tolerance &) const override {
1732 // Applies to any Boolean circuit. A multivalued (BID) circuit is handled
1733 // too: handlesMultivalued() is false, so the dispatcher rewrites the blocks
1734 // to independent Booleans before evaluate() and the general recursion never
1735 // meets a mulinput (the throw in footprintOf is now only a defensive net).
1736 return true;
1737 }
1738 double estimatedCost(const EvalContext &ctx, const Tolerance &tol) const override {
1739 const double S = static_cast<double>(ctx.circuit_size);
1740 // Approximate (DNF or general circuit): the anytime early stop caps the work
1741 // (and it is delta-independent); grows as eps tightens. This is the d-tree's
1742 // edge on a non-DNF circuit -- it returns certified bounds where the exact
1743 // compilers would do full work. NB the treewidth proxy is NOT used -- it
1744 // mispredicts this engine (cliques collapse fast under Shannon + subsumption,
1745 // low-w cycles do not).
1746 if(tol.kind != ToleranceKind::Exact && tol.epsilon > 0.) {
1747 // The general (non-DNF) path first computes every gate's footprint.
1748 const double footprint = ctx.dnf_ok_ ? 0.
1749 : kCostDTreeFootprint * S * static_cast<double>(ctx.n_inputs);
1750 return std::max(ctx.dtree_cost_floor_,
1751 kCostDTreeApprox * S / tol.epsilon + footprint);
1752 }
1753 // Exact: memoised Shannon compilation, ~S*m. Pessimistic vs tree-
1754 // decomposition (tighter constant) on low treewidth, so it is picked for
1755 // exact only where tree-decomposition bails (treewidth above its cap). Only
1756 // the monotone-DNF fast path competes for exact auto-selection; a non-DNF
1757 // exact request leaves the well-understood compilers (tree-decomposition /
1758 // d4 / possible-worlds) to choose, with the general recursion reachable
1759 // by-name -- generalising the *shape* of the bounds engine without retuning
1760 // the exact cost model (a separate item).
1761 if(!ctx.dnf_ok_)
1762 return std::numeric_limits<double>::infinity();
1763 const double m = static_cast<double>(ctx.dnf_num_clauses_ > 0
1764 ? ctx.dnf_num_clauses_ : 1);
1765 return std::max(ctx.dtree_cost_floor_, kCostDTreeExact * S * m);
1766 }
1767 double evaluate(EvalContext &ctx, const Tolerance &tol) const override {
1768 // Monotone-DNF circuits take the optimised clause path; everything else
1769 // (negation / EXCEPT, nested AND/OR, arbitrary sharing) takes the general
1770 // circuit recursion. Both are the same Olteanu-Huang-Koch anytime engine.
1771 std::vector<gate_t> clause_roots;
1772 std::vector<std::set<gate_t> > supports;
1773 const bool is_dnf = ctx.c.dnfShape(ctx.gate, clause_roots, supports);
1774 ctx.actual_method = "d-tree";
1775
1776 // Effective tolerance: a relative/additive PATH supplies it via `tol`; an
1777 // explicit by-name 'd-tree' is exact, unless an epsilon arg is given, which
1778 // is read as an additive interval half-width target.
1779 ToleranceKind kind = tol.kind;
1780 double eps = tol.epsilon;
1781 if(kind == ToleranceKind::Exact) {
1782 MethodArgs a = parse_method_args(ctx.args);
1783 if(a.has("epsilon")) {
1784 double dummy_delta = 0.;
1785 parse_eps_delta(a, "d-tree", eps, dummy_delta); // validates eps in (0,1]
1787 }
1788 }
1789
1790 // Tolerance -> absolute interval-width target for the recursion.
1791 double max_width;
1792 if(kind == ToleranceKind::Additive && eps > 0.) {
1793 // Additive eps: half-width <= eps means |est - p| <= eps.
1794 max_width = 2. * eps;
1795 } else if(kind == ToleranceKind::Relative && eps > 0.) {
1796 // Relative eps: with p >= L (the cheap lower bound), a half-width <=
1797 // eps*L gives |est - p| <= eps*L <= eps*p. The cheap lower bound is
1798 // dnfBounds on the DNF path; on the general path it is the leaf bound the
1799 // recursion returns for a trivially-wide target.
1800 double l0;
1801 if(is_dnf) {
1802 double u0;
1803 ctx.c.dnfBounds(supports, l0, u0);
1804 } else {
1805 l0 = provsql::dtreeBoundsCircuit(ctx.c, ctx.gate, 1.0).lower;
1806 }
1807 max_width = 2. * eps * l0;
1808 } else {
1809 max_width = 0.; // exact
1810 }
1811
1812 // Speculative-execution budget: convert the chooser's ms budget (the
1813 // next-best method's cost) into a subproblem cap, so the d-tree bails (throws,
1814 // chooser re-ranks it) rather than blowing up on a high-treewidth circuit its
1815 // cheap-feature cost estimate mis-rated. An explicit by-name call runs
1816 // unbounded (it is the user's deliberate choice, with no chooser fallback);
1817 // the debug GUC provsql.dtree_max_subproblems imposes an extra hard cap.
1818 unsigned long budget_steps = 0; // 0 = unbounded
1819 if(!ctx.explicitly_named && std::isfinite(ctx.cost_budget)) {
1820 const double ms_per_step = is_dnf ? kCostDTreeMsPerStepDnf
1822 budget_steps = static_cast<unsigned long>(
1823 std::max(1.0, ctx.cost_budget / ms_per_step));
1824 }
1826 unsigned long cap = static_cast<unsigned long>(provsql_dtree_max_subproblems);
1827 budget_steps = (budget_steps == 0) ? cap : std::min(budget_steps, cap);
1828 }
1829
1830 // Wall-clock backstop: ten times the budget, for a circuit whose
1831 // subproblems cost far more than the per-step calibration (heavy sharing,
1832 // as in a recursion's Boolean expansion). It never binds where the
1833 // calibration holds, so the step budget keeps the choice deterministic.
1834 double budget_ms = 0.;
1835 if(!ctx.explicitly_named && std::isfinite(ctx.cost_budget))
1836 budget_ms = std::max(50., 10. * ctx.cost_budget);
1837
1838 unsigned long steps = 0;
1839 provsql::DTreeInterval iv;
1840 try {
1841 iv = is_dnf
1842 ? provsql::dtreeBounds(ctx.c, std::move(supports), max_width, budget_steps,
1843 &steps, budget_ms)
1844 : provsql::dtreeBoundsCircuit(ctx.c, ctx.gate, max_width, budget_steps,
1845 &steps, budget_ms);
1846 } catch(CircuitException &e) {
1847 // Overran the budget: compete again at twice that, so the work wasted on
1848 // this method stays within a constant factor of what it finally spends.
1849 if(ctx.explicitly_named || !std::isfinite(ctx.cost_budget)
1851 throw;
1852 ctx.dtree_cost_floor_ = 2. * ctx.cost_budget;
1853 throw MethodRepricedException(e.what());
1854 }
1855 if(provsql_verbose >= 50)
1856 provsql_notice("calibrate kind=dtree path=%s S=%zu N=%zu steps=%lu budget=%lu",
1857 is_dnf ? "dnf" : "circuit", ctx.circuit_size, ctx.n_inputs,
1858 steps, budget_steps);
1859 const double est = 0.5 * (iv.lower + iv.upper);
1860
1861 // Deterministic certificate (delta = 0) whenever an approximation was
1862 // actually returned (the interval did not collapse to a point).
1863 if(iv.upper > iv.lower) {
1864 const double half = 0.5 * (iv.upper - iv.lower);
1865 if(kind == ToleranceKind::Relative && est > 0.)
1866 emit_guarantee("relative", half / est, 0., 0, -1, nullptr);
1867 else
1868 emit_guarantee("additive", half, 0., 0, -1, nullptr);
1869 }
1870 return est;
1871 }
1872};
1873
1874/// weightmc: backward-compatible alias for the weighted-model-counter path.
1875class WeightmcMethod : public ProbabilityMethod {
1876public:
1877 std::string name() const override { return "weightmc"; }
1878 ToleranceKind guaranteeKind() const override { return ToleranceKind::Relative; }
1879 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1880 std::string opt = wmc_opt_from_args(parse_method_args(ctx.args), "weightmc");
1881 emit_guarantee("relative", eps_from_wmc_opt(opt), -1., 0, -1, "weightmc");
1882 double r = ctx.c.wmcCount(ctx.gate, "weightmc", opt);
1883 ctx.actual_method = "weightmc";
1884 return r;
1885 }
1886};
1887
1888/// wmc: any registered weighted model counter, selected by tool=<name>.
1889class WmcMethod : public ProbabilityMethod {
1890public:
1891 std::string name() const override { return "wmc"; }
1892 ToleranceKind guaranteeKind() const override { return ToleranceKind::Relative; }
1893 double evaluate(EvalContext &ctx, const Tolerance &) const override {
1894 MethodArgs a = parse_method_args(ctx.args);
1895 std::string tool, tool_args;
1896 if(a.has("tool") || a.has("epsilon") || a.has("delta")) {
1897 reject_unknown_keys(a, {"tool", "epsilon", "delta"}, "wmc");
1898 tool = a.get("tool");
1899 if(tool.empty() && !a.positional.empty())
1900 tool = a.positional[0];
1901 if(tool.empty())
1902 provsql_error("method 'wmc' requires a tool (tool=<name>)");
1903 if(a.has("epsilon") || a.has("delta")) {
1904 double eps = 0.8, delta = 0.5; // validate ranges uniformly
1905 parse_eps_delta(a, "wmc", eps, delta);
1906 tool_args = a.get("delta") + ";" + a.get("epsilon");
1907 }
1908 } else {
1909 auto sep = ctx.args.find(';');
1910 tool = (sep == std::string::npos) ? ctx.args : ctx.args.substr(0, sep);
1911 tool_args = (sep == std::string::npos) ? std::string()
1912 : ctx.args.substr(sep + 1);
1913 }
1914 if(is_approx_wmc_tool(tool))
1915 emit_guarantee("relative", eps_from_wmc_opt(tool_args), -1., 0, -1,
1916 tool.c_str());
1917 double r = ctx.c.wmcCount(ctx.gate, tool, tool_args);
1918 // Report WHICH counter ran (e.g. "wmc:ganak"), mirroring "compilation:d4".
1919 ctx.actual_method = tool.empty() ? "wmc" : "wmc:" + tool;
1920 return r;
1921 }
1922};
1923
1924} // anonymous namespace
1925
1926void MethodCatalog::registerMethod(std::unique_ptr<ProbabilityMethod> m)
1927{
1928 methods_.push_back(std::move(m));
1929}
1930
1931// Base implementation: only the producesDD() methods override this.
1933{
1934 throw CircuitException("method '" + name()
1935 + "' does not construct a d-DNNF");
1936}
1937
1939{
1940 // The d-D portfolio reads only the Boolean view, so the generic-circuit
1941 // pointers are null (never dereferenced by interpret-as-dd /
1942 // tree-decomposition / compilation) and the request is the exact path.
1943 std::string no_args;
1944 EvalContext ctx{/*gc=*/nullptr, /*gc_root=*/gate_t{}, /*token=*/pg_uuid_t{},
1945 c, g, /*gc_to_bc=*/nullptr, /*inv_free_cert=*/false, no_args,
1946 /*explicitly_named=*/false,
1947 /*n_inputs=*/c.getInputs().size(),
1948 /*circuit_size=*/c.getNbGates()};
1950}
1951
1952const ProbabilityMethod *MethodCatalog::byName(const std::string &n) const
1953{
1954 for(const auto &m : methods_)
1955 if(m->name() == n)
1956 return m.get();
1957 return nullptr;
1958}
1959
1960/// Admissibility of a method's guarantee under a requested tolerance. The paths
1961/// nest Exact ⊂ Relative ⊂ Additive: a method is admissible iff its guarantee is at
1962/// least as tight as the request (an exact method serves any path -- "exact when
1963/// cheaper"; a relative method serves relative & additive; an additive method serves
1964/// only additive). This both widens the relative/additive portfolios to the
1965/// approximate members AND keeps the exact path (which calls chooseAndRun with an
1966/// Exact tolerance) from ever selecting an approximate method.
1967static bool toleranceAdmits(ToleranceKind request, ToleranceKind method)
1968{
1969 switch(request) {
1970 case ToleranceKind::Exact: return method == ToleranceKind::Exact;
1971 case ToleranceKind::Relative: return method != ToleranceKind::Additive;
1972 case ToleranceKind::Additive: return true;
1973 }
1974 return false;
1975}
1976
1977namespace {
1978
1979/// Uniform-cost search shared by chooseAndRun (returns a probability) and
1980/// chooseAndBuildDD (returns a d-DNNF artifact). @p run performs the chosen
1981/// method's work and returns the result of type @c R (calling @c evaluate or
1982/// @c buildDD respectively); everything else -- lazy feature acquisition, the
1983/// cheapest-first ranking, the speculative budget, and dropping a method that
1984/// throws -- is identical for both, so it lives here once.
1985template<class R, class Run, class Dropped>
1986R runPortfolio(EvalContext &ctx, const Tolerance &tol,
1987 std::vector<const ProbabilityMethod *> portfolio, Run run,
1988 Dropped dropped)
1989{
1990 // Each step either RUNS the cheapest ready method or ACQUIRES the cheapest
1991 // pending feature -- and we acquire a feature only when no ready method is
1992 // already cheaper than acquiring it (a feature-gated method then costs at
1993 // least that much anyway). So a feature costing more than the cheapest ready
1994 // method is never computed: 'independent' resolves a read-once circuit without
1995 // the treewidth proxy, after the cheaper dnfShape walk. A method that throws
1996 // when attempted is dropped (its implicit feature -- e.g. 'independent'
1997 // learning the circuit is not independent), unless it throws
1998 // MethodRepricedException, which keeps it at its new estimate; the last such
1999 // error propagates if the portfolio is exhausted.
2000 std::set<Feature> acquired;
2001 std::string last_error;
2002 bool have_last_error = false;
2003
2004 while(true) {
2005 // The cheapest ready (all required features acquired) and applicable method,
2006 // and the set of features still gating the not-ready ones.
2007 const ProbabilityMethod *best = nullptr;
2008 double best_cost = std::numeric_limits<double>::infinity();
2009 double second_cost = std::numeric_limits<double>::infinity();
2010 std::set<Feature> pending;
2011 for(const ProbabilityMethod *m : portfolio) {
2012 bool ready = true;
2013 for(Feature f : m->requiredFeatures())
2014 if(acquired.find(f) == acquired.end()) { ready = false; pending.insert(f); }
2015 if(!ready || !m->applicable(ctx, tol))
2016 continue;
2017 double cost = m->estimatedCost(ctx, tol);
2018 if(cost < best_cost) { second_cost = best_cost; best_cost = cost; best = m; }
2019 else if(cost < second_cost) { second_cost = cost; }
2020 }
2021 // Speculative-execution budget: bound the chosen method's work at the cost of
2022 // the next-cheapest ready alternative (infinity if it is the only one). A
2023 // budget-aware method (the d-tree) bails past this and the catch below drops
2024 // it to that alternative, so wasted work is at most ~the safe fallback's cost.
2025 ctx.cost_budget = second_cost;
2026
2027 // The cheapest feature we could acquire to reveal more method costs.
2028 bool have_pending = false;
2029 Feature cheapest_f = Feature::DnfShape;
2030 double cheapest_fc = std::numeric_limits<double>::infinity();
2031 for(Feature f : pending) {
2032 double fc = ctx.featureCost(f);
2033 if(fc < cheapest_fc) { cheapest_fc = fc; cheapest_f = f; have_pending = true; }
2034 }
2035
2036 // An evaluation outside the Boolean view is cheaper than anything left to
2037 // do here: leave it to the caller.
2038 if(std::min(best != nullptr ? best_cost
2039 : std::numeric_limits<double>::infinity(),
2040 have_pending ? cheapest_fc
2041 : std::numeric_limits<double>::infinity())
2042 > ctx.outside_cost)
2043 throw CircuitException(
2044 "an evaluation outside the Boolean circuit is cheaper");
2045
2046 if(best != nullptr && (!have_pending || best_cost <= cheapest_fc)) {
2047 // Run the cheapest method: nothing cheaper could be revealed by acquiring
2048 // a feature first. A Boolean-only method (handlesMultivalued() == false)
2049 // gets multivalued / BID blocks rewritten to independent Booleans first;
2050 // booleanSubcircuitProbability applies the same rule to a named method
2051 // (idempotent, and a no-op on a circuit with no mulinput gates).
2052 if(!best->handlesMultivalued())
2053 ctx.ensureMultivaluedRewritten();
2054 try {
2055 // Calibration (provsql.verbose_level >= 50): emit the raw cost parameters
2056 // and elapsed ms so each kCost can be fit so that cost ~ ms.
2057 if(provsql_verbose >= 50) {
2058 auto t0 = std::chrono::steady_clock::now();
2059 R r = run(best);
2060 double ms = std::chrono::duration<double, std::milli>(
2061 std::chrono::steady_clock::now() - t0).count();
2062 provsql_notice("calibrate kind=method which=%s S=%zu N=%zu m=%zu w=%u "
2063 "D=%u cost=%g ms=%g", best->name().c_str(),
2064 ctx.circuit_size, ctx.n_inputs, ctx.dnf_num_clauses_,
2065 ctx.tw_proxy_, ctx.tw_max_degree_, best_cost, ms);
2066 return r;
2067 }
2068 return run(best);
2069 } catch(MethodRepricedException &e) {
2071 throw;
2072 if(provsql_verbose >= 50)
2073 provsql_notice("calibrate kind=repriced which=%s S=%zu cost=%g "
2074 "budget=%g newcost=%g why=%s", best->name().c_str(),
2075 ctx.circuit_size, best_cost, second_cost,
2076 best->estimatedCost(ctx, tol), e.what());
2077 // The method stays in the running, so this is not its verdict: keep what
2078 // a dropped method reported, e.g., that no knowledge compiler is
2079 // installed, which is what the user can act on.
2080 if(!have_last_error) {
2081 last_error = e.what();
2082 have_last_error = true;
2083 }
2084 } catch(CircuitException &e) {
2086 throw; // a cancel / timeout -- do not silently try another method
2087 if(provsql_verbose >= 50)
2088 provsql_notice("calibrate kind=dropped which=%s S=%zu cost=%g "
2089 "budget=%g why=%s", best->name().c_str(),
2090 ctx.circuit_size, best_cost, second_cost, e.what());
2091 last_error = e.what();
2092 have_last_error = true;
2093 portfolio.erase(std::remove(portfolio.begin(), portfolio.end(), best),
2094 portfolio.end());
2095 if(std::optional<R> r = dropped(best))
2096 return std::move(*r);
2097 }
2098 } else if(have_pending) {
2099 if(provsql_verbose >= 50) {
2100 auto t0 = std::chrono::steady_clock::now();
2101 ctx.acquireFeature(cheapest_f);
2102 double ms = std::chrono::duration<double, std::milli>(
2103 std::chrono::steady_clock::now() - t0).count();
2104 provsql_notice("calibrate kind=feature which=%s S=%zu cost=%g ms=%g",
2105 cheapest_f == Feature::DnfShape ? "DnfShape"
2106 : "TreewidthProxy",
2107 ctx.circuit_size, cheapest_fc, ms);
2108 } else {
2109 ctx.acquireFeature(cheapest_f);
2110 }
2111 acquired.insert(cheapest_f);
2112 } else {
2113 // No ready method and nothing left to acquire: the portfolio is exhausted.
2114 if(have_last_error)
2115 throw CircuitException(last_error);
2116 throw CircuitException("no applicable probability method in the portfolio");
2117 }
2118 }
2119}
2120
2121} // anonymous namespace
2122
2124{
2125 std::vector<const ProbabilityMethod *> portfolio;
2126 for(const auto &m : methods_)
2127 if(m->inDefaultChain() && toleranceAdmits(tol.kind, m->guaranteeKind())
2128 // A delta == 0 ("deterministic") request admits only deterministic
2129 // methods: the (eps,delta) samplers cannot honour delta = 0 (their cost
2130 // model even masks this by falling back to a finite delta), so they must
2131 // be excluded by admissibility, not left to lose on cost.
2132 && (tol.delta > 0. || m->isDeterministic()))
2133 portfolio.push_back(m.get());
2134
2135 const auto keep = [](const ProbabilityMethod *) {
2136 return std::optional<double>();
2137 };
2138 const bool may_fold = evalOptActive(provsql_idp_fold, ctx)
2139 && tol.kind == ToleranceKind::Exact
2140 && !ctx.fold_component && !ctx.inv_free_cert
2141 && !std::isfinite(ctx.outside_cost)
2142 && rootRoute(ctx.gc, ctx.gc_root) == PROVSQL_ROUTE_NONE;
2143 if(!may_fold)
2144 return runPortfolio<double>(ctx, tol, std::move(portfolio),
2145 [&](const ProbabilityMethod *m){ return m->evaluate(ctx, tol); }, keep);
2146
2147 const std::vector<const ProbabilityMethod *> all = portfolio;
2148 const auto fold = [&](const ProbabilityMethod *failed)
2149 -> std::optional<double> {
2150 if(failed->name() != "independent")
2151 return std::nullopt;
2152 const BooleanGate type = ctx.c.getGateType(ctx.gate);
2153 if(type != BooleanGate::AND && type != BooleanGate::OR)
2154 return std::nullopt;
2155 if(!probCacheEligible(ctx.c, ctx.gate))
2156 return std::nullopt;
2157
2158 // Thrown where the root has nothing to fold: one group of children
2159 // sharing inputs.
2160 struct NothingToFold {};
2161
2162 std::vector<std::string> used;
2163 ProbFoldEval eval;
2164 eval.part = [&](BooleanCircuit &part, gate_t part_root, bool linked) {
2165 EvalContext sub{nullptr, gate_t{}, pg_uuid_t{}, part, part_root, nullptr,
2166 false, ctx.args, false, part.getInputs().size(),
2167 part.getNbGates()};
2168 sub.linked_group = linked;
2169 sub.fold_component = true;
2170 const double p = runPortfolio<double>(sub, tol, all,
2171 [&](const ProbabilityMethod *m){ return m->evaluate(sub, tol); },
2172 keep);
2173 if(std::find(used.begin(), used.end(), sub.actual_method) == used.end())
2174 used.push_back(sub.actual_method);
2175 return p;
2176 };
2177 eval.whole = []() -> double { throw NothingToFold(); };
2178 try {
2179 const double r = probFoldedProbability(ctx.c, ctx.gate, eval);
2180 std::string name = "fold";
2181 for(const std::string &u : used)
2182 if(!u.empty())
2183 name += "," + u;
2184 ctx.actual_method = name;
2185 return r;
2186 } catch(NothingToFold &) {
2187 // The portfolio this is called from goes on with the remaining methods
2188 // on the whole circuit. Running them here would run them twice when
2189 // they all fail, the caller trying them again after us.
2190 } catch(CircuitException &) {
2192 throw;
2193 // A part resisted every method: the caller tries the whole circuit.
2194 }
2195 // Either way the root is not folded again by the methods that follow,
2196 // which would only split it into the same groups.
2197 ctx.fold_component = true;
2198 return std::nullopt;
2199 };
2200 return runPortfolio<double>(ctx, tol, std::move(portfolio),
2201 [&](const ProbabilityMethod *m){ return m->evaluate(ctx, tol); }, fold);
2202}
2203
2205{
2206 // The d-D portfolio is the producesDD() methods (interpret-as-dd /
2207 // tree-decomposition / compilation): all exact, so no tolerance filtering.
2208 // interpret-as-dd is by-name-only for the probability chain (independent
2209 // subsumes it there) but IS the cheapest artifact route here, so it is
2210 // included via producesDD(), not inDefaultChain().
2211 std::vector<const ProbabilityMethod *> portfolio;
2212 for(const auto &m : methods_)
2213 if(m->producesDD())
2214 portfolio.push_back(m.get());
2215 return runPortfolio<dDNNF>(ctx, tol, std::move(portfolio),
2216 [&](const ProbabilityMethod *m){ return m->buildDD(ctx); },
2217 [](const ProbabilityMethod *) { return std::optional<dDNNF>(); });
2218}
2219
2221{
2222 static const MethodCatalog cat = [] {
2223 MethodCatalog c;
2224 // Exact portfolio (registration order is irrelevant -- the chooser sorts by
2225 // estimatedCost): independent, inversion-free, possible-worlds (2^N),
2226 // tree-decomposition, compilation. interpret-as-dd is NOT in the portfolio
2227 // -- it is redundant with independent (see InterpretAsDd).
2228 c.registerMethod(std::make_unique<IndependentMethod>());
2229 // The three planner-time routes: same sweep as 'independent', reported (and
2230 // invocable) under the name of the rewrite that produced the circuit.
2231 // Mutually exclusive with 'independent' and with each other via the root's
2232 // route tag, so the identical cost never has to be tie-broken.
2233 c.registerMethod(std::make_unique<RouteMethod>(
2234 PROVSQL_ROUTE_SQ_REWRITE, "sq-rewrite",
2235 "a provenance root produced by the safe-query "
2236 "(read-once) rewriter"));
2237 c.registerMethod(std::make_unique<RouteMethod>(
2238 PROVSQL_ROUTE_BOUNDED_JW, "bounded-jw",
2239 "a provenance root produced by the joint-width UCQ "
2240 "compiler"));
2241 c.registerMethod(std::make_unique<RouteMethod>(
2242 PROVSQL_ROUTE_REACHABILITY, "reachability",
2243 "a provenance root produced by the reachability "
2244 "compiler"));
2245 c.registerMethod(std::make_unique<InversionFreeMethod>());
2246 c.registerMethod(std::make_unique<MobiusMethod>());
2247 c.registerMethod(std::make_unique<TreeDecompositionMethod>());
2248 c.registerMethod(std::make_unique<CompilationMethod>());
2249 c.registerMethod(std::make_unique<PossibleWorldsMethod>());
2250 c.registerMethod(std::make_unique<SieveMethod>());
2251 c.registerMethod(std::make_unique<DTreeBoundsMethod>());
2252 // Approximate portfolio members. Admissibility (toleranceAdmits) keeps them out
2253 // of the exact path: monte-carlo (additive) serves only 'additive';
2254 // karp-luby / stopping-rule (relative) serve 'relative' and 'additive'.
2255 c.registerMethod(std::make_unique<MonteCarloMethod>());
2256 c.registerMethod(std::make_unique<KarpLubyMethod>());
2257 c.registerMethod(std::make_unique<StoppingRuleMethod>());
2258 // By-name-only methods (out of the auto-chooser): interpret-as-dd is redundant
2259 // with independent; weightmc / wmc are external subprocess counters needing a
2260 // tool argument, so they are not auto-spawned on a relative request.
2261 c.registerMethod(std::make_unique<InterpretAsDdMethod>());
2262 c.registerMethod(std::make_unique<WeightmcMethod>());
2263 c.registerMethod(std::make_unique<WmcMethod>());
2264 return c;
2265 }();
2266 return cat;
2267}
2268
2269/// Size of a circuit with recursions on cyclic data, and of its Boolean
2270/// expansion: the gates reachable from the root, plus, for each cyclic
2271/// component of k rows of an equation system, the 2 * (k-1) * terms gates of
2272/// the rounds the BoolExpr translation unrolls it into.
2274 double circuit_gates = 0.; ///< Gates reachable from the root
2275 double expanded_gates = 0.; ///< Gates of the Boolean expansion
2276};
2277
2279 gate_t root)
2280{
2282 std::unordered_set<gate_t> seen;
2283 std::vector<gate_t> stack{root};
2284 while(!stack.empty()) {
2285 const gate_t g = stack.back();
2286 stack.pop_back();
2287 if(!seen.insert(g).second)
2288 continue;
2289 e.circuit_gates += 1.;
2290 if(gc.getGateType(g) == gate_fixsystem) {
2291 const FixSystemLinear l = gc.linearizeFixSystem(g);
2292 std::vector<std::vector<std::size_t> > adj(l.n);
2293 for(std::size_t j = 0; j < l.n; ++j)
2294 for(const auto &t : l.out[j])
2295 adj[j].push_back(t.first);
2296 std::vector<std::size_t> comp_of(l.n);
2297 const auto comps = fixSystemComponents(adj);
2298 for(std::size_t c = 0; c < comps.size(); ++c)
2299 for(const auto v : comps[c])
2300 comp_of[v] = c;
2301 for(std::size_t c = 0; c < comps.size(); ++c) {
2302 if(comps[c].size() < 2)
2303 continue;
2304 double terms = 0.;
2305 for(const auto i : comps[c])
2306 for(const auto &t : l.in[i])
2307 if(comp_of[t.first] == c)
2308 terms += 1.;
2309 e.expanded_gates +=
2310 2. * static_cast<double>(comps[c].size() - 1) * terms;
2311 }
2312 }
2313 for(gate_t c : gc.getWires(g))
2314 stack.push_back(c);
2315 }
2317 return e;
2318}
2319
2321 const std::string &method,
2322 const std::string &args,
2323 bool inv_free_cert, const Tolerance &tol,
2324 bool mc_fallback,
2325 std::string *actual_method_out)
2326{
2327 const pg_uuid_t token = string2uuid(gc.getUUID(root));
2328 const bool is_path =
2329 method.empty() || method == "default" || method == "exact";
2330
2331 /* A recursion on cyclic data: its Boolean view expands every cyclic
2332 * component into rounds, which can be far larger than the circuit. An
2333 * approximation samples the equation systems directly when that is cheaper
2334 * than building the expansion (or when it would not fit); an exact answer
2335 * needs the expansion, and is refused when it would not fit. */
2336 bool skip_boolean_view = false;
2337 double outside_cost = std::numeric_limits<double>::infinity();
2338 if(circuitHasFixpoint(gc, root)) {
2339 const ExpansionEstimate e = estimateBooleanExpansion(gc, root);
2340 const bool too_large = e.expanded_gates > kMaxBooleanExpansion;
2341 if(tol.kind != ToleranceKind::Exact && tol.delta > 0.
2342 && tol.epsilon > 0.) {
2343 const double per_sample = tol.kind == ToleranceKind::Additive
2345 const double sampling = per_sample * e.circuit_gates
2346 * std::log(2.0 / tol.delta)
2347 / (tol.epsilon * tol.epsilon);
2348 skip_boolean_view =
2349 too_large || kCostBooleanExpansion * e.expanded_gates >= sampling;
2350 // Once built, the Boolean view's methods compete with the sampling.
2351 outside_cost = sampling;
2352 } else if(too_large) {
2353 if(mc_fallback)
2354 skip_boolean_view = true;
2355 else
2356 throw CircuitRefusal(
2357 PROVSQL_GAP, "recursion-expansion-too-large",
2358 "the Boolean circuit of this recursion on cyclic data would have "
2359 "about " + std::to_string(static_cast<long long>(e.expanded_gates))
2360 + " gates, too many to build "
2361 "for an exact probability; ask for an approximation instead "
2362 "('additive' or 'relative', or 'monte-carlo'), which solves the "
2363 "recursion in each sampled world");
2364 }
2365 }
2366
2367 // Boolean-view portfolio. Skip the build when the circuit carries random
2368 // variables (the BoolExpr translation drops gate_rv and rejects an RV
2369 // gate_cmp), or when a large sampleable HAVING aggregate under an
2370 // approximate request would force provsql_having's non-terminating
2371 // threshold-lineage expansion -- those go straight to the estimators below.
2372 const bool sampleable_agg = circuitHasUnresolvedSampleableAgg(gc, root);
2373 /* A contribution that is itself an aggregate result has no Boolean view at
2374 * all (its value is one per world, not a gate_value the translation can
2375 * read), so such a circuit goes straight to the estimators below rather than
2376 * meeting the semiring as an unresolved comparison. */
2377 const bool nested_agg = circuitHasNestedAggValue(gc, root);
2378 if (!skip_boolean_view && !circuitHasRV(gc, root) && !nested_agg &&
2379 !(sampleable_agg && tol.delta > 0.)) {
2380 try {
2381 gate_t gate;
2382 std::unordered_map<gate_t, gate_t> gc_to_bc;
2383 BooleanCircuit c = getBooleanCircuit(gc, token, gate, gc_to_bc);
2384 EvalContext ctx{&gc, root, token, c, gate, &gc_to_bc,
2385 inv_free_cert, args, /*explicitly_named=*/!is_path,
2386 /*n_inputs=*/c.getInputs().size(),
2387 /*circuit_size=*/c.getNbGates()};
2388 ctx.outside_cost = outside_cost;
2389 double result;
2390 if (is_path) {
2391 // The empty / "default" / "exact" method runs the cost-ordered
2392 // auto-chooser under the requested tolerance.
2393 result = MethodCatalog::instance().chooseAndRun(ctx, tol);
2394 } else {
2396 if (m == nullptr)
2397 provsql_error("Wrong method '%s' for probability evaluation",
2398 method.c_str());
2399 // A Boolean-only method named explicitly gets multivalued / BID
2400 // blocks rewritten first (same rule as runPortfolio).
2401 if (!m->handlesMultivalued())
2403 result = m->evaluate(ctx, tol);
2404 }
2405 if (actual_method_out != nullptr)
2406 *actual_method_out = ctx.actual_method;
2407 return result;
2408 } catch (const semiring::SemiringException &) {
2409 // Boolean translation met a raw RV comparator: fall to the estimators.
2410 if (tol.kind == ToleranceKind::Exact && !mc_fallback) throw;
2411 } catch (const CircuitException &) {
2412 // Portfolio exhausted / Boolean view unbuildable: estimators or raise.
2413 if (tol.kind == ToleranceKind::Exact && !mc_fallback) throw;
2414 }
2415 }
2416
2417 // No Boolean view: the tolerance-appropriate generic-circuit estimator.
2418 if (tol.delta == 0. && tol.kind != ToleranceKind::Exact)
2420 "a deterministic (delta = 0) guarantee is not available for this "
2421 "circuit: it carries random-variable or HAVING-aggregate gates, for "
2422 "which only the (eps,delta) samplers apply -- use delta > 0");
2423 if (tol.kind == ToleranceKind::Relative) {
2424 double result;
2425 std::string am;
2426 run_stopping_rule(gc, root, parse_method_args(args), result, am);
2427 if (actual_method_out != nullptr) *actual_method_out = am;
2428 return result;
2429 }
2430 if (tol.kind == ToleranceKind::Additive) {
2431 if (actual_method_out != nullptr) *actual_method_out = "monte-carlo";
2432 return monteCarloRV(
2433 gc, root, static_cast<int>(monte_carlo_samples(parse_method_args(args))));
2434 }
2435 // Exact request with no Boolean view: the moment path's fixed-sample MC
2436 // over the base RVs (mc_fallback). probability_evaluate's exact arm routes
2437 // its RV circuits to monte-carlo upstream and passes mc_fallback = false,
2438 // so it raises here rather than silently sampling.
2439 if (!mc_fallback || provsql_rv_mc_samples <= 0)
2440 throw CircuitException(
2441 "booleanSubcircuitProbability: a random-variable comparator could not "
2442 "be resolved to a Boolean and no Monte Carlo fallback is available "
2443 "(provsql.rv_mc_samples = 0)");
2444 if (actual_method_out != nullptr) *actual_method_out = "monte-carlo";
2445 return monteCarloRV(gc, root, static_cast<int>(provsql_rv_mc_samples));
2446}
2447
2448} // namespace provsql
2449
2450// ---------------------------------------------------------------------------
2451// Three-path tolerance surface (exact / relative / additive).
2452//
2453// The user grants a tolerance via the method name -- "exact" (alias for the
2454// empty/default method), "relative" (a (1±eps) guarantee), "additive"
2455// (|p̂-p| <= eps) -- and the system picks the mechanism, rather than naming an
2456// algorithm (named methods stay available as the EXPLAIN-level escape hatch).
2457// Admissibility nests exact ⊂ relative ⊂ additive, so every path returns an
2458// EXACT value when one is cheaply available ("exact when cheaper"): an exact
2459// result satisfies any (eps,delta).
2460//
2461// The relative/additive estimators run on the GenericCircuit (RV-aware), so they
2462// live here rather than in the BooleanCircuit catalog; folding them in behind a
2463// lazy Boolean build is the clean follow-up.
2464// ---------------------------------------------------------------------------
2465
2466/// Whole-circuit (eps,delta)-relative estimate via the stopping rule (shared by
2467/// the explicit 'stopping-rule' method and the 'relative' path's estimator).
2468///
2469/// Complexity O(S / (p * eps^2) * ln(1/delta)): the Dagum rule draws ~Y1/p
2470/// whole-circuit worlds, each an O(S) evalBool. The 1/p factor makes the cost
2471/// NOT a priori computable from static features -- a precise cost needs a
2472/// p-lower-bound feature -- which is why this estimator stays a path fallback
2473/// rather than a cost-ranked portfolio member for now.
2474static void run_stopping_rule(GenericCircuit &gc, gate_t gc_root,
2475 const MethodArgs &a, double &result,
2476 std::string &actual_method)
2477{
2478 SampleSpec s = parse_sample_spec(a, "stopping-rule");
2479 if(s.fixed)
2480 provsql_error("the relative / stopping-rule estimator is adaptive: give "
2481 "epsilon=E[,delta=D][,max_samples=M], not a fixed sample "
2482 "count");
2483 const unsigned long cap = s.has_max ? s.max_samples : 10000000UL;
2484 unsigned long used = 0;
2485 bool reached = false;
2486 result = provsql::monteCarloRVStopping(gc, gc_root, s.eps, s.delta, cap, used,
2487 reached);
2488 if(reached || used == 0) {
2489 emit_guarantee("relative", s.eps, s.delta, used, -1, "stopping-rule");
2490 } else {
2491 const double eps_add = sqrt(log(2.0 / 0.05) / (2.0 * used));
2492 provsql_warning("relative estimate: reached the %lu-sample cap before the "
2493 "(epsilon=%g, delta=%g) relative target; reporting the "
2494 "additive guarantee at the samples spent (the event is "
2495 "likely rarer than this budget resolves -- raise "
2496 "max_samples)", cap, s.eps, s.delta);
2497 emit_guarantee("additive", eps_add, 0.05, used, -1, "stopping-rule");
2498 }
2499 actual_method = "stopping-rule";
2500}
2501
2502/// Record the method just used in the @c provsql.last_eval_method GUC
2503/// (comma-separated, deduplicated across calls in the session) so callers can
2504/// inspect which evaluation strategy the default auto-selection settled on.
2505/// Shared by the main dispatch and the early-returning gate_mobius route.
2506static void record_last_eval_method(const std::string &actual_method)
2507{
2508 if(actual_method.empty())
2509 return;
2510 std::string current = provsql_last_eval_method ? provsql_last_eval_method : "";
2511 bool changed = false;
2512 size_t start = 0;
2513 while(start <= actual_method.size()) {
2514 size_t end = actual_method.find(',', start);
2515 if(end == std::string::npos)
2516 end = actual_method.size();
2517 const std::string name = actual_method.substr(start, end - start);
2518 // Whole-name match: "tree-decomposition" is not already listed because
2519 // "cache:tree-decomposition" is.
2520 if(!name.empty()
2521 && ("," + current + ",").find("," + name + ",") == std::string::npos) {
2522 if(!current.empty()) current += ",";
2523 current += name;
2524 changed = true;
2525 }
2526 start = end + 1;
2527 }
2528 if(changed)
2529 SetConfigOption("provsql.last_eval_method", current.c_str(),
2530 PGC_USERSET, PGC_S_SESSION);
2531}
2532
2533/**
2534 * @brief Core implementation of probability evaluation for a circuit token.
2535 * @param token UUID of the root provenance gate.
2536 * @param method Evaluation method name (e.g. "independent", "monte-carlo").
2537 * @param args Additional arguments for the chosen method.
2538 * @param isnull Out-param set to @c true when the result is SQL NULL (a
2539 * conditioned token whose evidence has probability zero); may
2540 * be @c NULL when the caller does not need null-propagation.
2541 * @return Float8 Datum containing the computed probability (undefined
2542 * when @p isnull is set to @c true).
2543 */
2544/// Name of the exact route that enumerates the worlds of the inputs on the
2545/// circuit as it is, comparisons and aggregates evaluated per world.
2546static const char *const kPossibleWorldsAgg = "possible-worlds-aggregates";
2547/// Most inputs it enumerates the 2^n worlds of.
2548static const unsigned kPossibleWorldsAggMaxInputs = 20;
2549
2550/// The most contributions an aggregation gate below @p root has, 0 when
2551/// neither a comparison nor an aggregation is there. The worst case of the
2552/// Boolean view is the enumeration of the subsets of those contributions, so
2553/// this is what the enumeration of the worlds of the inputs competes with.
2554static unsigned maxAggContributions(const GenericCircuit &gc, gate_t root)
2555{
2556 std::unordered_set<gate_t> seen;
2557 std::stack<gate_t> todo;
2558 unsigned most = 0;
2559 bool any = false;
2560 todo.push(root);
2561 while(!todo.empty()) {
2562 gate_t g = todo.top();
2563 todo.pop();
2564 if(!seen.insert(g).second) continue;
2565 const gate_type t = gc.getGateType(g);
2566 if(t == gate_cmp || t == gate_agg) {
2567 any = true;
2568 if(t == gate_agg)
2569 most = std::max(most, static_cast<unsigned>(gc.getWires(g).size()));
2570 }
2571 for(gate_t c : gc.getWires(g)) todo.push(c);
2572 }
2573 return any ? std::max(most, 1u) : 0;
2574}
2575
2577 (pg_uuid_t token, const string &method, const string &args, bool *isnull)
2578{
2579 if(isnull != nullptr)
2580 *isnull = false;
2581 // Load the GenericCircuit once: we need it for the RV-detection
2582 // dispatch below, and getBooleanCircuit() reuses it internally so we
2583 // pay no extra cost compared to the previous flow. Universal
2584 // cmp-resolution passes (RangeCheck) have already been applied
2585 // inside getGenericCircuit when the provsql.simplify_on_load GUC is
2586 // on (the default), so the circuit we receive here is already
2587 // peephole-pruned for any "always true / always false" comparator.
2590 gate_t gc_root = gc.getGate(uuid2string(token));
2591
2592 // Conditioning gate (the | / cond operator, uuid carrier): a terminal
2593 // gate_conditioned with children [target, evidence, joint], joint =
2594 // times(target, evidence). Its probability is the conditional
2595 // P(target ∧ evidence) / P(evidence) = P(joint) / P(evidence). Both
2596 // sub-tokens are ordinary semiring gates already in the store (the joint
2597 // is materialised at construction), so each is evaluated by an ordinary
2598 // recursive call -- correlation between target and evidence is exact
2599 // because content-addressing makes a shared base tuple the same input
2600 // gate in both circuits. Impossible evidence (P(evidence) = 0) yields
2601 // SQL NULL. The gate is terminal: a conditioned token can never be a
2602 // child of a semiring gate (the constructors refuse it), so we only ever
2603 // meet it at the root here.
2604 if(gc.getGateType(gc_root) == gate_conditioned) {
2605 const auto &w = gc.getWires(gc_root);
2606 if(w.size() == 2)
2607 provsql_error("probability_evaluate: this is a conditioned distribution "
2608 "(a random_variable / agg_token X | C), not a Boolean "
2609 "event; query it with expected / variance / moment / "
2610 "support, which report the conditional distribution");
2611 if(w.size() != 3)
2612 provsql_error("probability_evaluate: malformed conditioned gate "
2613 "(expected 3 children [target, evidence, joint], got %zu)",
2614 w.size());
2615 pg_uuid_t evidence = string2uuid(gc.getUUID(w[1]));
2616 pg_uuid_t joint = string2uuid(gc.getUUID(w[2]));
2617 bool ev_null = false, jt_null = false;
2618 double pe = DatumGetFloat8(
2619 probability_evaluate_internal(evidence, method, args, &ev_null));
2620 if(ev_null || pe == 0.) {
2621 if(isnull != nullptr)
2622 *isnull = true;
2623 return (Datum) 0; // impossible (or undefined) evidence -> NULL
2624 }
2625 double pj = DatumGetFloat8(
2626 probability_evaluate_internal(joint, method, args, &jt_null));
2627 if(jt_null) {
2628 if(isnull != nullptr)
2629 *isnull = true;
2630 return (Datum) 0;
2631 }
2632 double r = pj / pe;
2633 if(r > 1.) r = 1.; else if(r < 0.) r = 0.;
2634 PG_RETURN_FLOAT8(r);
2635 }
2636
2637 // Möbius-inversion route (safe-UCQ Möbius cancellation): a gate_mobius root
2638 // is a signed combination Σ_i coeff_i · P(child_i) over certified-independent
2639 // islands -- a probability-only shortcut layered over the normal provenance,
2640 // which it carries as a designated "L:<uuid>" lineage child (modelled on
2641 // 'inversion-free'). The default / exact / empty request and the granted-
2642 // tolerance paths (relative / additive) run the fast Möbius route, as does an
2643 // explicit 'mobius': the route is exact and linear, so it trivially meets any
2644 // tolerance -- "exact when cheap", which is exactly what those paths want, and
2645 // it avoids falling through to an FPRAS on the (#P-hard) literal lineage. Any
2646 // OTHER named method is evaluated on the literal lineage (the same exact
2647 // probability via, e.g., possible-worlds or monte-carlo -- slower, but the
2648 // user keeps every method).
2649 if(gc.getGateType(gc_root) == gate_mobius) {
2650 const bool is_path =
2651 method.empty() || method == "default" || method == "exact"
2652 || method == "relative" || method == "additive";
2653 if(is_path || method == "mobius") {
2654 BooleanCircuit dummy;
2655 gate_t dummygate{};
2656 std::unordered_map<gate_t, gate_t> dummymap;
2657 provsql::EvalContext ctx{&gc, gc_root, token, dummy, dummygate, &dummymap,
2658 /*inv_free_cert=*/false, args,
2659 /*explicitly_named=*/!is_path, 0, 0};
2660 double r = provsql::MethodCatalog::instance().byName("mobius")->evaluate(
2661 ctx, provsql::Tolerance{});
2662 // This route returns early (below the main dispatch's recording block),
2663 // so record the method here -- otherwise last_eval_method stays empty.
2665 PG_RETURN_FLOAT8(r);
2666 }
2667 // Another named method: fall through to the literal lineage (the "L:"
2668 // child, read from the raw circuit) and recurse with the requested method.
2669 const std::string lineage = mobiusLineageOf(token);
2670 if(lineage.empty())
2671 provsql_error("method '%s': this Möbius-route token carries no literal "
2672 "lineage (it was built measure-only); only the default / "
2673 "'mobius' method applies", method.c_str());
2674 return probability_evaluate_internal(string2uuid(lineage), method, args,
2675 isnull);
2676 }
2677
2678 // Inversion-free tractability certificate: the planner wraps the per-row
2679 // provenance root in a transparent annotation gate carrying the serialised
2680 // SafeCert recipe. Its presence routes the default probability chain through
2681 // the structured-d-DNNF builder (after independentEvaluation, before
2682 // tree-decomposition) and is required by the explicit 'inversion-free'
2683 // method. The recipe is read here (early, before the simplifier passes); the
2684 // per-input order keys are collected at the dispatch point, where the
2685 // GenericCircuit->BooleanCircuit mapping is available.
2686 bool inv_free_cert = false;
2687 {
2688 std::string ex = gc.getExtra(gc_root);
2689 if (!ex.empty() && ex[0] == SAFE_CERT_EXTRA_PREFIX_RECIPE) {
2690 SafeCert *cert = safe_cert_parse(ex.c_str());
2691 if (cert != nullptr && cert->kind == CERT_INVERSION_FREE) {
2692 inv_free_cert = true;
2693 // Internal per-evaluation diagnostic (the certificate round-trips from
2694 // the planner), not a result-comprehension message: keep it at the
2695 // detector's debug-trace level (>= 30) so it stays out of the level-5
2696 // floor the Studio eval strip applies.
2697 if (provsql_verbose >= 30)
2698 provsql_notice("inversion-free certificate read back from circuit "
2699 "root: %d atoms, %d classes, root_class=%d",
2700 cert->natoms, cert->nclasses, cert->root_class);
2701 }
2702 }
2703 }
2704
2705 // Resolve every RV / HAVING comparator into Boolean structure via the
2706 // single shared pipeline (value simplifier + island decomposer +
2707 // AnalyticEvaluator + the closed-form HAVING cmp evaluators + the
2708 // always-true rewrite). The probability path runs the full pipeline;
2709 // the scalar-moment path calls the same function with simplify/decompose
2710 // off (see ComparatorResolution.h).
2711 provsql::resolveComparators(gc, gc_root, /*simplify=*/true,
2712 /*decompose=*/true);
2713 /* After every resolution pass has run, any gate_rv left in the
2714 * circuit reaches the BoolExpr translation in getBooleanCircuit
2715 * unchanged; that walk recurses into the surrounding gate_cmp and
2716 * calls semiring.value() on the gate_value side, producing the
2717 * generic "This semiring does not support value gates." error.
2718 * Detect that here and raise a message that names the actual
2719 * root cause: the analytical evaluators couldn't fold the RV
2720 * leaves away, and the MC fallback that would have decided the
2721 * surrounding cmp is either disabled (rv_mc_samples = 0) or
2722 * wasn't able to close the gap. HAVING-style cmps over gate_agg
2723 * don't contain gate_rv, so this check leaves them for
2724 * provsql_having. */
2725 /* The empty / "default" request lets the system choose the mechanism,
2726 * so it may silently fall back to Monte Carlo for comparators the
2727 * analytic pre-passes deliberately leave unresolved. An explicit
2728 * "exact" request is a contract for an exact value and must NOT be
2729 * quietly downgraded to an MC estimate; it raises like a named method. */
2730 const bool mc_default = method.empty() || method == "default";
2731 if (method != "monte-carlo" && method != "stopping-rule"
2732 && method != "relative" && method != "additive"
2733 && provsql::circuitHasRV(gc, gc_root)) {
2734 if (provsql_rv_mc_samples <= 0) {
2736 "probability_evaluate: a comparison over random variables "
2737 "could not be resolved analytically; raise "
2738 "provsql.rv_mc_samples above 0 to enable the Monte Carlo "
2739 "fallback, or call probability_evaluate(..., 'monte-carlo', "
2740 "<n>) directly");
2741 } else if (!mc_default) {
2743 "probability_evaluate: a comparison over random variables "
2744 "could not be resolved analytically and the hybrid evaluator "
2745 "left it unresolved; call probability_evaluate(..., "
2746 "'monte-carlo', <n>) directly for an MC estimate");
2747 }
2748 /* Default request with the MC budget available: the comparators the
2749 * analytic pre-passes deliberately left unresolved (a mixture cmp
2750 * whose selector is shared / compound, or another intricate
2751 * correlated shape) are handled by the RV-aware whole-circuit Monte
2752 * Carlo sampler, which couples every shared leaf and selector per
2753 * iteration. Fall through; the dispatch below passes
2754 * mc_fallback = mc_default so booleanSubcircuitProbability routes
2755 * to monteCarloRV. */
2756 }
2757
2758 /* A comparison or an aggregation the resolution passes left in the
2759 * circuit: the Boolean view of it (getBooleanCircuit, through
2760 * provsql_having) enumerates the subsets of the comparison's own
2761 * contributors, one Boolean term each -- millions of gates for the rank of
2762 * a row among 21 candidates, where the contributors read the same handful
2763 * of input tuples. With fewer inputs than a comparison has contributions,
2764 * enumerate the worlds of the inputs on the circuit as it is instead:
2765 * exact, and 2^n evaluations of a circuit of its original size. With as
2766 * many inputs or fewer, the resolution is the cheaper of the two (and its
2767 * closed forms cheaper still), so it keeps the circuit. An explicitly
2768 * named method keeps its own route. */
2769 {
2770 const bool named = !(method.empty() || method == "default");
2771 const unsigned contributions = maxAggContributions(gc, gc_root);
2772 /* A contribution that is itself an aggregate result: the resolution passes
2773 * decline it whatever the number of contributions, so the comparison of
2774 * the counts below does not apply and the enumeration is the only exact
2775 * route. It gets the whole bound. */
2776 const bool nested_agg = provsql::circuitHasNestedAggValue(gc, gc_root);
2777 if((!named || method == kPossibleWorldsAgg) && contributions > 0) {
2778 /* At most as many inputs as the resolution would have contributions to
2779 * enumerate subsets of, and never more than the bound */
2780 const unsigned cap =
2781 (named || nested_agg)
2783 : std::min(kPossibleWorldsAggMaxInputs, contributions - 1);
2784 std::optional<double> p;
2785 try {
2786 p = provsql::enumerateBooleanProbability(gc, gc_root, cap);
2787 } catch(const CircuitException &) {
2788 if(named) throw;
2789 p = std::nullopt; /* a gate it cannot evaluate: fall back */
2790 }
2791 if(p) {
2793 return Float8GetDatum(*p);
2794 }
2795 if(named)
2796 provsql_error("probability_evaluate: method %s needs a circuit whose "
2797 "only random sources are at most %u input tuples",
2799 }
2800 }
2801
2802 double result;
2803 // Records which probability method actually produced the result, so it can
2804 // be exposed through the provsql.last_eval_method GUC (useful when method
2805 // is left empty and the default auto-selection picks one).
2806 string actual_method;
2807
2808 try {
2809 provsql_interrupt_scope interrupt_scope;
2810 // GenericCircuit-level estimators (the relative / additive paths and their
2811 // explicit-method aliases) run before the BoolExpr translation in
2812 // getBooleanCircuit (which drops gate_rv and rejects RV gate_cmp), so they
2813 // sit at the top here rather than in the BooleanCircuit method catalog.
2814 //
2815 // 'relative' / 'stopping-rule': whole-circuit (eps,delta)-RELATIVE
2816 // probability via the Dagum-Karp-Luby-Ross stopping rule (the universal
2817 // relative estimator -- plain Boolean / RV / HAVING agg). The 'relative'
2818 // path first tries an exact result when one is cheaply available.
2819 if(method == "relative" || method == "additive") {
2820 // Three-path tolerance request, routed through the SAME cost chooser as the
2821 // exact path -- just with a wider admissible set (toleranceAdmits): a
2822 // 'relative' request's portfolio is the exact methods (exact when cheaper) +
2823 // the relative estimators (karp-luby on a DNF, the universal stopping rule);
2824 // 'additive' additionally admits fixed-sample monte-carlo. The chooser picks
2825 // the cheapest, so a tuple-independent circuit resolves exactly via
2826 // 'independent', a small DNF exactly via 'sieve', and a hard/large circuit
2827 // falls to the bounded-cost estimator -- generalising the old
2828 // independent-only "exact when cheaper" to the whole exact portfolio.
2829 const provsql::ToleranceKind tk = (method == "relative")
2832 SampleSpec s = parse_sample_spec(parse_method_args(args), method.c_str());
2833 provsql::Tolerance tol{tk, s.eps, s.delta};
2834
2835 // Delegate to the single Boolean-probability entry point under this
2836 // tolerance: it runs the exact portfolio through the Boolean view when
2837 // one can be built (a tuple-independent circuit resolves exactly via
2838 // 'independent', a small DNF via 'sieve'), and the (eps,delta)
2839 // generic-circuit estimator (stopping rule for 'relative', fixed-sample
2840 // monteCarloRV for 'additive') on an RV / large-aggregate circuit.
2842 gc, gc_root, /*method=*/"", args, inv_free_cert, tol,
2843 /*mc_fallback=*/false, &actual_method);
2844 } else if(method == "stopping-rule") {
2845 run_stopping_rule(gc, gc_root, parse_method_args(args), result,
2846 actual_method);
2847 } else if(method == "monte-carlo"
2848 && (provsql::circuitHasRV(gc, gc_root)
2850 || provsql::circuitHasFixpoint(gc, gc_root))) {
2851 // RV-aware (fixed-sample, additive) Monte Carlo. Also the route for a
2852 // surviving sample-faithful HAVING comparator (any aggregate -- the
2853 // apx-safe corner): the sampler evaluates the gate_agg directly, so a
2854 // large-magnitude aggregate is estimated without the non-terminating
2855 // threshold-lineage expansion.
2856 unsigned long samples = monte_carlo_samples(parse_method_args(args));
2857 result = provsql::monteCarloRV(gc, gc_root, static_cast<int>(samples));
2858 } else if(mc_default && provsql::circuitHasRV(gc, gc_root)) {
2859 // Default request over a circuit that still carries random-variable
2860 // comparators after the analytic pre-passes: those are the shapes
2861 // the pre-passes deliberately declined to marginalise (a mixture cmp
2862 // whose selector is shared with the rest of the circuit, or another
2863 // intricate correlated form). The RV-aware whole-circuit Monte Carlo
2864 // sampler is the correct, general evaluator -- it couples every
2865 // shared base RV and mixture selector per iteration. Only the empty
2866 // / "default" request falls back here; an explicit "exact" request
2867 // was already refused above rather than silently downgraded to MC.
2868 result = provsql::monteCarloRV(
2869 gc, gc_root, static_cast<int>(provsql_rv_mc_samples));
2870 actual_method = "monte-carlo";
2871 } else {
2872 // Boolean-circuit path: the single central entry point builds the
2873 // Boolean view (HAVING semantics + BoolExpr translation) and runs the
2874 // method portfolio (chooseAndRun for the empty / "default" / "exact"
2875 // aliases, byName otherwise). mc_fallback is false here so an
2876 // unresolved RV comparator surfaces its diagnostic rather than
2877 // silently sampling (the moment path opts into the MC fallback).
2879 gc, gc_root, method, args, inv_free_cert, provsql::Tolerance{},
2880 /*mc_fallback=*/false, &actual_method);
2881 }
2882 } catch(CircuitException &e) {
2883 // If the exception was raised because a query cancel or statement
2884 // timeout is pending (the in-process loops throw "Interrupted" off the
2885 // provsql_interrupted flag rather than longjmp through their C++ stack),
2886 // let PG report its native 57014 with the specific reason instead of the
2887 // generic "Interrupted". For any other CircuitException no cancel is
2888 // pending, so CHECK_FOR_INTERRUPTS is a no-op and we report it as-is.
2889 // The scope has restored the handler as the try was left.
2891 provsql_error("%s", e.what());
2892 }
2893
2894 // Record the method just used (see record_last_eval_method) so callers can
2895 // inspect which evaluation strategy the default auto-selection settled on.
2896 record_last_eval_method(actual_method);
2897
2898 // Avoid rounding errors that make probability outside of [0,1]
2899 if(result>1.)
2900 result=1.;
2901 else if(result<0.)
2902 result=0.;
2903
2904 PG_RETURN_FLOAT8(result);
2905}
2906
2907/** @brief PostgreSQL-callable wrapper for probability_evaluate(). */
2908Datum probability_evaluate(PG_FUNCTION_ARGS)
2909{
2910 provsql_sync_tool_registry(); // honour persisted tool-registry overrides
2911 try {
2912 provsql_interrupt_scope interrupt_scope;
2913 Datum token = PG_GETARG_DATUM(0);
2914 string method;
2915 string args;
2916
2917 if(PG_ARGISNULL(0))
2918 PG_RETURN_NULL();
2919
2920 if(!PG_ARGISNULL(1)) {
2921 text *t = PG_GETARG_TEXT_P(1);
2922 method = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
2923 }
2924
2925 if(!PG_ARGISNULL(2)) {
2926 text *t = PG_GETARG_TEXT_P(2);
2927 args = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
2928 }
2929
2930 bool isnull = false;
2931 Datum result =
2932 probability_evaluate_internal(*DatumGetUUIDP(token), method, args, &isnull);
2933 if(isnull)
2934 PG_RETURN_NULL();
2935 return result;
2936 } catch(const semiring::SemiringGateException &e) {
2938 /* A gate the resolution passes left for the semiring itself: a
2939 * comparison of aggregate results none of them could resolve, whose
2940 * value gates the Boolean translation then meets. A shape ProvSQL does
2941 * not support, not an internal error. */
2942 provsql_unsupported(PROVSQL_GAP, "comparison-unresolved", "probability_evaluate: a comparison ProvSQL could not "
2943 "resolve remains in the circuit (%s): supported are a "
2944 "comparison of an aggregate with a constant, between "
2945 "numeric aggregates, and between two array_agg results",
2946 e.what());
2947 } catch(const std::exception &e) {
2949 provsql_error("probability_evaluate: %s", e.what());
2950 } catch(...) {
2952 provsql_error("probability_evaluate: Unknown exception");
2953 }
2954
2955 PG_RETURN_NULL();
2956}
2957
2958/**
2959 * @brief PostgreSQL-callable wrapper for the d-tree leaf bound:
2960 * @c probability_bounds(token uuid, OUT lower float8, OUT upper float8).
2961 *
2962 * Returns a cheap certified interval @c [lower,upper] with @c lower ≤ Pr ≤ upper
2963 * for the probability of the DNF-shaped circuit rooted at @p token, via
2964 * @c BooleanCircuit::dnfBounds (Olteanu-Huang-Koch Fig. 3). Errors when the circuit
2965 * is not a monotone DNF over input leaves (the leaf-bound heuristic is
2966 * DNF-specific); the future d-tree engine will recurse on non-DNF roots.
2967 */
2968Datum probability_bounds(PG_FUNCTION_ARGS)
2969{
2971 try {
2972 provsql_interrupt_scope interrupt_scope;
2973 if(PG_ARGISNULL(0))
2974 PG_RETURN_NULL();
2975 pg_uuid_t token = *DatumGetUUIDP(PG_GETARG_DATUM(0));
2976
2977 gate_t root;
2978 BooleanCircuit c = getBooleanCircuit(token, root);
2979
2980 std::vector<gate_t> clause_roots;
2981 std::vector<std::set<gate_t> > supports;
2982 if(!c.dnfShape(root, clause_roots, supports))
2983 provsql_error("probability_bounds applies only to a DNF-shaped circuit "
2984 "(a monotone OR-of-ANDs over input leaves); negation, "
2985 "comparison, aggregation, random-variable and "
2986 "multivalued-input gates are not supported");
2987
2988 double lower, upper;
2989 c.dnfBounds(supports, lower, upper);
2990
2991 TupleDesc tupdesc;
2992 if(get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
2993 provsql_error("probability_bounds: expected composite return type");
2994 tupdesc = BlessTupleDesc(tupdesc);
2995
2996 Datum values[2] = { Float8GetDatum(lower), Float8GetDatum(upper) };
2997 bool nulls[2] = { false, false };
2998 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
2999 } catch(const std::exception &e) {
3001 provsql_error("probability_bounds: %s", e.what());
3002 } catch(...) {
3004 provsql_error("probability_bounds: Unknown exception");
3005 }
3006
3007 PG_RETURN_NULL();
3008}
Exact closed-form HAVING COUNT(*) op C probability over safe-join lineage – the recursive marginal-ve...
Closed-form CDF resolution for trivial gate_cmp shapes.
Boolean-expression (lineage formula) semiring.
Boolean provenance circuit with support for knowledge compilation.
constexpr unsigned DNNF_CERT_INFO
d-DNNF certificate value for the (gate-type-specific) per-gate info field.
BooleanGate
Gate types for a Boolean provenance circuit.
@ OR
Logical disjunction of child gates.
@ AND
Logical conjunction of child gates.
@ IN
Input (variable) gate representing a base tuple.
static CircuitCache cache
Process-local singleton circuit gate cache.
BooleanCircuit getBooleanCircuit(GenericCircuit &gc, pg_uuid_t token, gate_t &gate, std::unordered_map< gate_t, gate_t > &gc_to_bc)
Build a BooleanCircuit from an already-loaded GenericCircuit.
void applyProbabilisticSimplification(GenericCircuit &gc)
Simplify a loaded circuit for a probability readout.
GenericCircuit getGenericCircuit(pg_uuid_t token)
Build a GenericCircuit from the mmap store rooted at token.
Build in-memory circuits from the mmap-backed persistent store.
gate_t
Strongly-typed gate identifier.
Definition Circuit.h:53
The single comparator-resolution pipeline and the single Boolean-subcircuit probability entry point,...
Closed-form Poisson-binomial CDF resolution for HAVING COUNT(*) op C gate_cmps.
Anytime interval-bounds probability for monotone DNFs (d-trees).
Strongly connected components of the dependency graph of an equation system (a recursive query,...
std::vector< std::vector< std::size_t > > fixSystemComponents(const std::vector< std::vector< std::size_t > > &out)
Strongly connected components of a directed graph, in the order in which equations along its edges ca...
Semiring-agnostic in-memory provenance circuit.
Peephole simplifier for continuous gate_arith sub-circuits.
Closed-form probability resolution for HAVING MIN(a) op C and MAX(a) op C gate_cmps.
Monte Carlo sampling over a GenericCircuit, RV-aware.
Cache of compiled d-DNNFs, and folding of independent parts.
Catalog of probability-evaluation methods (Strategy + registry).
Support-based bound check for continuous-RV comparators.
Abstract semiring interface for provenance evaluation.
In-process structured-d-DNNF construction over a query-derived variable order, for the inversion-free...
Closed-form probability resolution for HAVING SUM(a) op C gate_cmps via a weighted-sum DP.
Tree decomposition of a Boolean circuit for knowledge compilation.
Fix macro conflicts between PostgreSQL headers and the C++ STL/Boost.
Boolean circuit for provenance formula evaluation.
double karpLubyStopping(const std::vector< gate_t > &clauses, const std::vector< std::set< gate_t > > &supports, double eps, double delta, unsigned long max_samples, unsigned long &samples_used, bool &reached_target) const
Karp-Luby FPRAS with the self-adjusting stopping rule (adaptive sample count for a relative (eps,...
const std::set< gate_t > & getInputs() const
Return the set of input (IN) gate IDs.
double karpLuby(const std::vector< gate_t > &clauses, const std::vector< std::set< gate_t > > &supports, unsigned long samples) const
Karp-Luby FPRAS estimate of a DNF-shaped circuit's probability (fixed sample budget,...
dDNNF compilation(gate_t g, std::string compiler, std::string *resolved=nullptr) const
Compile the sub-circuit rooted at g to a dDNNF via an external tool.
void dnfBounds(const std::vector< std::set< gate_t > > &clauses, double &lower, double &upper) const
Cheap certified probability interval [lower,upper] of a monotone DNF, without compiling it (Olteanu-H...
bool dnfShape(gate_t g, std::vector< gate_t > &clauses, std::vector< std::set< gate_t > > &supports) const
Detect the DNF shape the Karp-Luby FPRAS requires.
static std::string checkCompiler(std::string compiler)
Exception type thrown by circuit operations on invalid input.
Definition Circuit.h:382
virtual char const * what() const noexcept
Return the error message as a C-string.
Definition Circuit.h:396
CircuitException(const std::string &m)
Construct with a descriptive error message.
Definition Circuit.h:390
A refusal by design, or a known gap, rather than an error.
Definition Circuit.h:409
std::vector< gate_t > & getWires(gate_t g)
Return a mutable reference to the child-wire list of gate g.
Definition Circuit.h:311
gateType getGateType(gate_t g) const
Return the type of gate g.
Definition Circuit.h:301
uuid getUUID(gate_t g) const
Return the UUID string associated with gate g.
Definition Circuit.hpp:65
gate_t getGate(const uuid &u)
Return (or create) the gate associated with UUID u.
Definition Circuit.hpp:50
std::vector< gate_t >::size_type getNbGates() const
Return the total number of gates in the circuit.
Definition Circuit.h:252
FixSystemLinear linearizeFixSystem(gate_t sys) const
The equations of the gate_fixsystem sys, as linear forms over the gates that do not depend on its unk...
std::string getExtra(gate_t g) const
Return the string extra for gate g.
double getProb(gate_t g) const
Return the probability for gate g.
std::pair< unsigned, unsigned > getInfos(gate_t g) const
Return the integer annotation pair for gate g.
Top-down structured-d-DNNF builder over a query-derived variable order.
const dDNNF & dnnf() const
The constructed d-DNNF (root set, simplified).
static unsigned degeneracyLowerBound(const BooleanCircuit &bc, unsigned &max_degree)
Cheap degeneracy lower bound on the treewidth of bc's primal graph.
static constexpr int MAX_TREEWIDTH
Maximum supported treewidth.
A d-DNNF circuit supporting exact probabilistic and game-theoretic evaluation.
Definition dDNNF.h:71
double probabilityEvaluation() const
Compute the exact probability of the d-DNNF being true.
Definition dDNNF.cpp:141
Registry of ProbabilityMethod objects.
const ProbabilityMethod * byName(const std::string &name) const
Exact match on name(); nullptr if absent.
std::vector< std::unique_ptr< ProbabilityMethod > > methods_
double chooseAndRun(EvalContext &ctx, const Tolerance &tol) const
Run the auto-chooser for tol: the portfolio methods admissible for the tolerance and applicable,...
void registerMethod(std::unique_ptr< ProbabilityMethod > m)
static const MethodCatalog & instance()
The process-wide catalog, lazily populated with the built-in methods.
dDNNF chooseAndBuildDD(EvalContext &ctx, const Tolerance &tol) const
The d-DNNF analogue of chooseAndRun: cost-select among the producesDD() portfolio (interpret-as-dd / ...
Thrown by a method that gave up under its budget but learned a tighter cost estimate: the chooser kee...
CircuitException(const std::string &m)
Construct with a descriptive error message.
Definition Circuit.h:390
Strategy interface: one concrete subclass per probability method.
virtual dDNNF buildDD(EvalContext &ctx) const
Build the d-DNNF this method constructs (only when producesDD()).
virtual double evaluate(EvalContext &ctx, const Tolerance &tol) const =0
Run the method, returning the probability.
virtual bool handlesMultivalued() const
True iff the method evaluates the raw circuit, including multivalued (BID / gate_mulinput) gates,...
virtual std::string name() const =0
Stable identifier used for byName lookup and the provsql.last_eval_method report.
The SIGINT handler installed for the lifetime of the object, the previous one restored as it ends (a ...
Exception thrown when a semiring operation is not supported.
Definition Semiring.h:55
virtual char const * what() const noexcept
Return the error message as a C-string.
Definition Semiring.h:69
A gate kind this semiring does not interpret (a comparison, a semimodule multiplication,...
Definition Semiring.h:84
Constructs a d-DNNF from a Boolean circuit and its tree decomposition.
Helpers for invoking external command-line tools.
Provenance evaluation helper for HAVING-clause circuits.
Shared declaration for the Möbius-route probability sweep.
double probFoldedProbability(const BooleanCircuit &c, gate_t root, const ProbFoldEval &eval)
Probability of the circuit below root, folding the independent groups of AND and OR gates from the ro...
static const double kCostDnfShapeFeature
static const double kCostSieve
static const double kCostDTreeFootprint
DTreeInterval dtreeBounds(const BooleanCircuit &c, Clauses clauses, double max_width, unsigned long budget, unsigned long *steps_out, double budget_ms)
Definition DTree.cpp:297
static const size_t kPossibleWorldsSanityMax
Sanity bound on the reachable-input count for the auto-chosen 2^N possible-worlds enumeration: above ...
double booleanSubcircuitProbability(GenericCircuit &gc, gate_t root, const std::string &method, const std::string &args, bool inv_free_cert, const Tolerance &tol, bool mc_fallback, std::string *actual_method_out)
Probability of the Boolean function rooted at root in gc – THE single entry point over the method por...
static const double kCostKarpLuby
std::optional< double > enumerateBooleanProbability(const GenericCircuit &gc, gate_t root, unsigned max_inputs)
The probability of root, exactly, over the possible worlds of the circuit as it is: the alternative t...
DTreeInterval dtreeBoundsCircuit(const BooleanCircuit &c, gate_t root, double max_width, unsigned long budget, unsigned long *steps_out, double budget_ms)
Certified probability interval of an arbitrary Boolean circuit, refined to a target width (the d-tree...
Definition DTree.cpp:680
static const double kCostDTreeExact
static const double kCostTwProxyFeature
bool circuitHasNestedAggValue(const GenericCircuit &gc, gate_t root)
Whether a contribution of an aggregate is itself an aggregate result (a gate_semimod whose M side is ...
static const double kCostDTreeMsPerStepGeneral
static const double kCostCompilationFloor
static bool toleranceAdmits(ToleranceKind request, ToleranceKind method)
Admissibility of a method's guarantee under a requested tolerance.
double monteCarloRVStopping(const GenericCircuit &gc, gate_t root, double eps, double delta, unsigned long max_samples, unsigned long &samples_used, bool &reached_target)
Whole-circuit (eps,delta)-relative probability via the Dagum-Karp-Luby-Ross stopping rule.
static const double kCostStoppingRule
static const double kCostPossibleWorlds
bool circuitHasUnresolvedSampleableAgg(const GenericCircuit &gc, gate_t root)
Whether a surviving gate_agg exists and every one is sample-faithful (SUM / AVG / MIN / MAX / COUNT –...
Feature
A circuit feature a method's cost/applicability estimate depends on, but that is not free to acquire.
static const double kCompilationMinLimitMs
static const double kCostDTreeApprox
static const double kCostInversionFree
ToleranceKind
The contract the user grants – the "path".
static ExpansionEstimate estimateBooleanExpansion(const GenericCircuit &gc, gate_t root)
static const double kCostTreeDecomp
static const double kCostDTreeMsPerStepDnf
static const double kMaxBooleanExpansion
static double pow2_clamped(size_t k)
2^k with the exponent clamped to keep the cost finite (a clamped exponent still sorts the method dead...
bool circuitHasFixpoint(const GenericCircuit &gc, gate_t root)
Whether a gate_fixpoint (a row of a recursion on cyclic data) is reachable from root.
static const double kCostMonteCarlo
static const double kCostCompilation
static const double kCostBooleanExpansion
double monteCarloRV(const GenericCircuit &gc, gate_t root, unsigned samples)
Run Monte Carlo on a circuit that may contain gate_rv leaves.
double probCachedProbability(const BooleanCircuit &c, gate_t root, const ProbCacheCompileFn &compile, bool *ran_compiler, const ProbCacheOptions &options)
Probability of the circuit below root through the fold and the cache.
static const double kCompilationBudgetFactor
bool probCacheEligible(const BooleanCircuit &c, gate_t root)
Whether the circuit below root is one the cache and the fold handle: AND, OR and NOT gates over input...
bool circuitHasRV(const GenericCircuit &gc, gate_t root)
Walk the circuit reachable from root looking for any gate_rv.
dDNNF makeDDAuto(BooleanCircuit &c, gate_t g)
Cost-select a d-DNNF construction route for gate g of Boolean circuit c and build it – the default ma...
void resolveComparators(GenericCircuit &gc, gate_t root, bool simplify, bool decompose)
Run the comparator-resolution pipeline on gc, rewriting every gate_cmp (RV comparison,...
static const size_t kSieveSanityMaxClauses
Largest clause count for which the auto-chosen sieve (2^m inclusion-exclusion) is admitted (matches B...
static const double kCostIndependent
Datum probability_evaluate(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for probability_evaluate().
static Datum probability_evaluate_internal(pg_uuid_t token, const string &method, const string &args, bool *isnull)
static std::map< gate_t, int > inversion_free_rank(const std::map< gate_t, StructuredDNNFBuilder::InputKey > &keys)
Flatten the per-input order keys into a total rank for the structured builder's order-only constructo...
static const char *const kPossibleWorldsAgg
Core implementation of probability evaluation for a circuit token.
double mobius_probability_of(pg_uuid_t token)
External entry point for the Möbius-route probability sweep (declared in mobius_evaluate....
Datum probability_bounds(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for the d-tree leaf bound: probability_bounds(token uuid,...
static const unsigned kPossibleWorldsAggMaxInputs
Most inputs it enumerates the 2^n worlds of.
static void record_last_eval_method(const std::string &actual_method)
Record the method just used in the provsql.last_eval_method GUC (comma-separated, deduplicated across...
dDNNF buildInversionFreeDDNNF(pg_uuid_t token)
Compile a query certified inversion-free to its structured d-DNNF.
static bool collect_inversion_free_keys(const GenericCircuit &gc, gate_t gc_root, const std::unordered_map< gate_t, gate_t > &gc_to_bc, const BooleanCircuit &c, gate_t bc_root, std::map< gate_t, StructuredDNNFBuilder::InputKey > &out)
Collect the inversion-free per-input order keys for the structured builder.
static void run_stopping_rule(GenericCircuit &gc, gate_t gc_root, const MethodArgs &a, double &result, std::string &actual_method)
Whole-circuit (eps,delta)-relative estimate via the stopping rule (shared by the explicit 'stopping-r...
static unsigned maxAggContributions(const GenericCircuit &gc, gate_t root)
The most contributions an aggregation gate below root has, 0 when neither a comparison nor an aggrega...
bool provsql_absorptive_provenance
Derived flag: the session's provenance class is 'absorptive' or 'boolean' – licenses constructions so...
Definition provsql.c:154
int provsql_verbose
Verbosity level; controlled by the provsql.verbose_level GUC.
Definition provsql.c:115
bool provsql_simplify_on_load
Run universal cmp-resolution passes when getGenericCircuit returns; controlled by the provsql....
Definition provsql.c:138
bool provsql_inversion_free
Insert the inversion-free structured-d-DNNF path into the default probability chain (after independen...
Definition provsql.c:152
char * provsql_last_eval_method
Last probability evaluation method(s) used; exposed via provsql.last_eval_method.
Definition provsql.c:119
int provsql_rv_mc_samples
Default sample count for analytical-evaluator MC fallbacks; 0 disables fallback (callers raise instea...
Definition provsql.c:126
int provsql_dtree_max_subproblems
Debug/safety hard cap on d-tree subproblems before it bails (0 = off; the chooser auto-budgets at the...
Definition provsql.c:128
int provsql_idp_fold
Backing variable of provsql.idp_fold: when an AND or OR root is split into independent groups evaluat...
Definition provsql.c:141
bool provsql_interrupted
Set by provsql_sigint_handler: this backend received a cancel.
Definition provsql.c:111
bool provsql_boolean_provenance
Derived flag: the session's provenance class is 'boolean' – enables the Boolean-only machinery (safe-...
Definition provsql.c:153
int provsql_prob_cache
Backing variable of provsql.prob_cache: when the per-backend cache of compiled d-DNNFs,...
Definition provsql.c:139
#define PROVSQL_GAP
#define provsql_error(fmt,...)
Report a fatal ProvSQL error and abort the current transaction.
#define provsql_unsupported(scope, tag, fmt,...)
Refuse a query ProvSQL cannot track, and abort the transaction.
#define provsql_warning(fmt,...)
Emit a ProvSQL warning message (execution continues).
#define provsql_notice(fmt,...)
Emit a ProvSQL informational notice (execution continues).
void provsql_cancel_if_interrupted(void)
Raise PG's cancel if the evaluation stopped for one; nothing otherwise.
Cancellation of the long C++ evaluation loops.
Background worker and IPC primitives for mmap-backed circuit storage.
Shared-memory segment and inter-process pipe management.
Core types, constants, and utilities shared across ProvSQL.
@ PROVSQL_EVAL_OPT_ON
Also applied to a method called by name.
@ PROVSQL_EVAL_OPT_AUTO
Applied by the default method only (default).
@ gate_annotation
Transparent single-child wrapper carrying a query-level annotation in extra (inversion-free certifica...
@ gate_mobius
Signed Möbius combination: a MEASURE-only gate carrying one integer coefficient per child (in extra,...
@ gate_conditioned
Conditioning marker with two children [target, evidence]: measure-only, probability_evaluate returns ...
@ gate_fixsystem
Linear equation system x_i = f_i(x) of a recursive query, one equation per derived tuple: wires [x_1,...
@ gate_assumed
Structural marker over a single child whose sub-circuit was computed under a Boolean-provenance assum...
provsql_route
Tags identifying the planner-time route that produced a circuit.
@ PROVSQL_ROUTE_BOUNDED_JW
Joint-width UCQ compiler (src/UCQJointCompiler.h).
@ PROVSQL_ROUTE_SQ_REWRITE
Hierarchical-CQ read-once rewrite (src/safe_query.c).
@ PROVSQL_ROUTE_NONE
No route rewrite: ordinary lineage.
@ PROVSQL_ROUTE_REACHABILITY
Recursive-reachability compiler (src/reachability_evaluate.cpp).
static const char * provsql_route_name(provsql_route route)
The name of a route, as the probability dispatcher reports it and as the annotation wrapper of a mate...
pg_uuid_t string2uuid(const string &source)
Parse a UUID string into a pg_uuid_t.
string uuid2string(pg_uuid_t uuid)
Format a pg_uuid_t as a std::string.
C++ utility functions for UUID manipulation.
SafeCert * safe_cert_parse(const char *str)
Parse a C-prefixed recipe string (as produced by safe_cert_serialise and read back from an annotation...
bool safe_cert_key_parse(const char *str, SafeCertKey *out)
Parse a K-prefixed order-key string into out.
Tractability certificate for the inversion-free UCQ(OBDD) path.
@ CERT_INVERSION_FREE
Inversion-free UCQ(OBDD) over TID inputs.
#define SAFE_CERT_EXTRA_PREFIX_RECIPE
Discriminator prefixes for the annotation gate's extra payload.
In-memory provenance circuit with semiring-generic evaluation.
std::size_t n
Number of unknowns.
std::vector< std::vector< std::pair< std::size_t, std::vector< gate_t > > > > in
Terms of each equation.
std::vector< std::vector< std::pair< std::size_t, std::vector< gate_t > > > > out
Terms, by unknown read.
const char * sec
const char * root
Query-derived order recipe for the structured-d-DNNF builder.
int nclasses
Number of (compacted) equivalence classes.
int root_class
Compacted id of the root class (touches every atom).
int natoms
Number of atoms (range-table entries).
SafeCertKind kind
Structured per-input order key carried by the planner's markers.
Per-evaluation circuit state threaded to a method's evaluate().
double cost_budget
Speculative-execution budget: the estimated cost (in the chooser's ms-ish units) of the next-cheapest...
double treedec_cost_floor_
Lower bound on tree-decomposition's cost, raised when the parts it builds (islands,...
bool hasFeature(Feature f) const
double featureCost(Feature f) const
Heuristic acquisition cost of f, in the same work units as a method's estimatedCost (so the chooser c...
double compilation_spent_ms_
Time, in ms, the external compiler has run in the current attempt.
size_t n_inputs
input count N (O(1) cost feature)
double dtree_cost_floor_
Lower bound on the d-tree's cost, raised each time it overruns a budget.
std::unordered_map< gate_t, gate_t > * gc_to_bc
bool explicitly_named
invoked via byName (vs the default chain)
double outside_cost
Cost of an evaluation outside this Boolean view (sampling the equation systems of a recursion directl...
double treedec_spent_
Cost of the parts tree-decomposition has built in the current attempt.
size_t circuit_size
gate count S, the circuit-size parameter (O(1))
double compilation_cost_floor_
Lower bound on compilation's cost, raised when the external compiler is stopped for running past its ...
Size of a circuit with recursions on cyclic data, and of its Boolean expansion: the gates reachable f...
double expanded_gates
Gates of the Boolean expansion.
double circuit_gates
Gates reachable from the root.
What probCachedProbability may do, and what it reports back.
Definition ProbCache.h:121
bool use_cache
Look compiled d-DNNFs up, and store new ones.
Definition ProbCache.h:122
What a call to probCachedProbability actually did, so the caller can report it instead of the method ...
Definition ProbCache.h:110
How probFoldedProbability evaluates what it cannot fold.
Definition ProbCache.h:133
std::function< double()> whole
Probability of the whole circuit, when its root has nothing to fold.
Definition ProbCache.h:139
std::function< double(BooleanCircuit &, gate_t, bool)> part
Probability of a part, given as a circuit of its own and its root; the flag tells a group of several ...
Definition ProbCache.h:137
bool evaluate(const std::vector< long > &values, const std::vector< bool > &mask, long constant, ComparisonOperator op, std::unique_ptr< Aggregator > aggregator)
Evaluate whether the aggregation of values masked by mask satisfies op constant.
Definition subset.cpp:367
void provsql_sync_tool_registry()
Rebuild the in-memory registry as "compiled seed overlaid with the provsql.tool_overrides rows"...
Reload the in-memory external-tool registry from its persistent overrides.