sverify-duckdb 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,387 @@
1
+ """sverify's DuckDB engine (#1189): its SQL dialect (`sverify_duckdb.dialect`,
2
+ `DUCKDB`), its runner on the process's database (`sverify_duckdb.engine`), the
3
+ lowering proved for every plan, and the table store (`DuckDBStore`),
4
+ registered as the `ProfilePlugin` `PLUGIN` under the entry-point group
5
+ `sverify.profiles`. DuckDB is sverify's default engine.
6
+
7
+ DuckDB's settings: sverify runs each plan on a cursor of its own on the
8
+ process's database (`sverify_duckdb.engine`), so a session's `SET` on another
9
+ cursor leaves it alone; `SET GLOBAL` reaches it, and that is what the check
10
+ sees. Not checked, since no choice depends on them: display settings, threads
11
+ (the order of a double `SUM`, `sum_order`, which every route allows within
12
+ the plan's bound), and `TimeZone` and `Calendar`, which the written SQL never
13
+ reads (plans with time-zone-aware timestamps are refused, duckdb-time-zones).
14
+ `dialect_compatibility_mode` and `regex_match_operator_semantics` wait on a
15
+ check of DuckDB's source.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import threading
22
+ from collections.abc import Sequence
23
+ from typing import Any
24
+
25
+ import duckdb
26
+ import pyarrow as pa
27
+
28
+ from sverify import _duckdb, black_box
29
+ from sverify._arrow_state import ArrowOps
30
+ from sverify._scan import Resident, _q
31
+ from sverify._store import State
32
+ from sverify._unsupported import RANGE_GUARD
33
+ from sverify._weighted import WEIGHT, _same_rows
34
+ from sverify.profiles import ProfilePlugin, Setting
35
+
36
+ _R15 = tuple(
37
+ f"duckdb-R15-{n}"
38
+ for n in (
39
+ "atan2",
40
+ "digests",
41
+ "double-arith",
42
+ "double-modulus",
43
+ "elementary",
44
+ "int-arith",
45
+ "int-divide",
46
+ "int-modulus",
47
+ "math-domain",
48
+ "regexp",
49
+ "round-digits",
50
+ "round",
51
+ "shift-left",
52
+ "shift-right",
53
+ )
54
+ )
55
+
56
+ #: The settings DuckDB's profile assumes.
57
+ SETTINGS: tuple[Setting, ...] = (
58
+ Setting(
59
+ "default_null_order",
60
+ ("nulls_last",),
61
+ "refuse",
62
+ ("duckdb-F2",),
63
+ "where NULLs sort in a key without a placement (null_order), and in "
64
+ "FIRST/LAST(... ORDER BY) and list_sort",
65
+ ("null_order", "list_null_order"),
66
+ ),
67
+ Setting(
68
+ "default_order",
69
+ ("ascending", "asc"),
70
+ "refuse",
71
+ (),
72
+ "the direction of a sort key without one",
73
+ ("null_order", "list_null_order"),
74
+ ),
75
+ Setting(
76
+ "integer_division",
77
+ (False,),
78
+ "refuse",
79
+ ("duckdb-F1",),
80
+ "whether `/` of integers divides as integers (division_type)",
81
+ ("division_type",),
82
+ ),
83
+ Setting(
84
+ "error_on_division_by_zero",
85
+ (True,),
86
+ "refuse",
87
+ ("duckdb-R2", "duckdb-R3", "duckdb-R4", *_R15),
88
+ "what a division by zero gives (on_division_by_zero): `//` and `%` give NULL "
89
+ "instead of raising; deprecated in DuckDB 2.0.0, still read and still in "
90
+ "effect there",
91
+ ("on_division_by_zero",),
92
+ ),
93
+ Setting(
94
+ "ieee_floating_point_ops",
95
+ (True,),
96
+ "refuse",
97
+ ("duckdb-R4", "duckdb-R5", *_R15),
98
+ "NaN and ±inf from double operations (nan_creation)",
99
+ ("nan_creation", "float_overflow"),
100
+ ),
101
+ Setting(
102
+ "default_collation",
103
+ ("",),
104
+ "refuse",
105
+ ("engines/duckdb/replay/collate.json",),
106
+ "how strings compare; NOCASE may change starts_with, strpos and replace",
107
+ ),
108
+ Setting(
109
+ "scalar_subquery_error_on_multiple_rows",
110
+ (True,),
111
+ "refuse",
112
+ ("engines/duckdb/replay/subquery.json",),
113
+ "whether a scalar subquery with several rows raises or takes one",
114
+ ),
115
+ Setting(
116
+ "enable_optimizer",
117
+ (True,),
118
+ "refuse",
119
+ ("engines/duckdb/replay/settings.json",),
120
+ "which rows a raising expression sees",
121
+ ),
122
+ Setting(
123
+ "disabled_optimizers",
124
+ ("",),
125
+ "refuse",
126
+ ("engines/duckdb/replay/settings.json",),
127
+ "which rows a raising expression sees",
128
+ ),
129
+ Setting(
130
+ "preserve_insertion_order",
131
+ (True,),
132
+ "warn",
133
+ ("engines/duckdb/replay/order.json",),
134
+ "the order of rows without an ORDER BY, which no route relies on",
135
+ ),
136
+ )
137
+
138
+
139
+ def _run(
140
+ con: Any, plan_json: str, session: Any, *, keep: bool, finite: bool, tie_free: bool
141
+ ) -> Any:
142
+ from sverify.engine import read_tables
143
+ from sverify_duckdb import engine as duckdb_engine
144
+
145
+ # DuckDB reads `Scan` and `Resident` tables where they are.
146
+ tables = {t: con.get(t) for t in read_tables(json.loads(plan_json))}
147
+ if keep:
148
+ return duckdb_engine.run(plan_json, tables, keep=True, finite=finite)
149
+ return duckdb_engine.run(plan_json, tables, finite=finite)
150
+
151
+
152
+ def _run_tables(
153
+ plan_json: str, tables: Any, *, guard_free: bool = False, finite: bool = True
154
+ ) -> Any:
155
+ from sverify_duckdb import engine as duckdb_engine
156
+
157
+ if guard_free:
158
+ raise ValueError("no theorem covers DuckDB's writer without its guards")
159
+ return duckdb_engine.run(plan_json, tables, finite=finite)
160
+
161
+
162
+ def _version() -> str | None:
163
+ import duckdb
164
+
165
+ return duckdb.__version__
166
+
167
+
168
+ def _read_settings(names: Sequence[str], session: Any) -> dict[str, Any]:
169
+ from sverify_duckdb import engine as duckdb_engine
170
+
171
+ return duckdb_engine.settings(names)
172
+
173
+
174
+ def _restore(setting: Setting) -> str:
175
+ v = setting.expected[0]
176
+ value = f"'{v}'" if isinstance(v, str) else str(v).lower()
177
+ return f"SET GLOBAL {setting.name} = {value}"
178
+
179
+
180
+ def _dialect() -> Any:
181
+ from sverify_duckdb.dialect import DUCKDB
182
+
183
+ return DUCKDB
184
+
185
+
186
+ class DuckDBStore(ArrowOps):
187
+ # Its handle: a table DuckDB holds (`Resident`), or an Arrow batch read in.
188
+ """The state as a table DuckDB holds (`Resident`): merges leave their
189
+ result in DuckDB, and the view's rows are a DuckDB view of it.
190
+
191
+ A refresh changes the state in place, at the cost of the change
192
+ (`apply`): the state rows equal to a row of the change (`matching`) are
193
+ added to the change by the merge plan, and replace those rows, for every
194
+ view in one transaction. The state then holds each row once with its
195
+ weight, as a full merge leaves it."""
196
+
197
+ keep = True
198
+ _db: duckdb.DuckDBPyConnection | None = None
199
+ _lock = threading.Lock()
200
+
201
+ def _sql(self, sql: str, *, kind: str = "TABLE", reads: tuple[Resident, ...] = ()) -> Resident:
202
+ """A new resident holding the result of `sql` (or with `kind`
203
+ "VIEW", a view of it)."""
204
+ with DuckDBStore._lock:
205
+ if DuckDBStore._db is None:
206
+ DuckDBStore._db = _duckdb.cursor()
207
+ db = DuckDBStore._db
208
+ _duckdb.collect(db)
209
+ name = Resident.new_name()
210
+ db.execute(f"CREATE {kind} main.{_q(name)} AS {sql}")
211
+ schema = db.sql(f"SELECT * FROM main.{_q(name)} LIMIT 0").to_arrow_table().schema
212
+ return Resident(name, schema, kind, reads)
213
+
214
+ def keep_table(self, table: pa.Table) -> Resident:
215
+ """An Arrow table, held by DuckDB."""
216
+ with DuckDBStore._lock:
217
+ if DuckDBStore._db is None:
218
+ DuckDBStore._db = _duckdb.cursor()
219
+ db = DuckDBStore._db
220
+ _duckdb.collect(db)
221
+ name = Resident.new_name()
222
+ db.register("__sverify_keep", table)
223
+ try:
224
+ db.execute(f"CREATE TABLE main.{_q(name)} AS SELECT * FROM __sverify_keep")
225
+ finally:
226
+ db.unregister("__sverify_keep")
227
+ return Resident(name, table.schema)
228
+
229
+ def weighted(self, rows: pa.Table | Resident, weight: int = 1) -> State:
230
+ if not isinstance(rows, Resident):
231
+ return super().weighted(rows, weight)
232
+ w = f"CAST({weight} AS BIGINT) AS {_q(WEIGHT)}"
233
+ return self._sql(f"SELECT *, {w} FROM {rows.ref}")
234
+
235
+ def negated(self, z: State) -> State:
236
+ if not isinstance(z, Resident):
237
+ return super().negated(z)
238
+ cols = ", ".join(_q(c) for c in z.schema.names if c != WEIGHT)
239
+ return self._sql(f"SELECT {cols}, -{_q(WEIGHT)} AS {_q(WEIGHT)} FROM {z.ref}")
240
+
241
+ def expanded(self, z: State) -> pa.Table | Resident:
242
+ if not isinstance(z, Resident):
243
+ return super().expanded(z)
244
+ cols = ", ".join(f"s.{_q(c)}" for c in z.schema.names if c != WEIGHT)
245
+ sql = f"SELECT {cols} FROM {z.ref} s, range(s.{_q(WEIGHT)})"
246
+ return self._sql(sql, kind="VIEW", reads=(z,))
247
+
248
+ def copy(self, z: Resident) -> Resident:
249
+ """A new table with the rows of `z`."""
250
+ return self._sql(f"SELECT * FROM {z.ref}")
251
+
252
+ def apply(self, updates: list[tuple[Resident, pa.Table, pa.Table]]) -> None:
253
+ """For each `(state, change, merged)`, in one transaction: delete
254
+ the rows of `state` equal to a row of `change`, and insert `merged`
255
+ (those rows plus the change, by the merge plan)."""
256
+ with DuckDBStore._lock:
257
+ if DuckDBStore._db is None:
258
+ DuckDBStore._db = _duckdb.cursor()
259
+ db = DuckDBStore._db
260
+ _duckdb.collect(db)
261
+ db.execute("BEGIN TRANSACTION")
262
+ try:
263
+ for state, change, merged in updates:
264
+ keys = [c for c in state.schema.names if c != WEIGHT]
265
+ db.register("__sverify_change", change)
266
+ db.register("__sverify_merged", merged)
267
+ try:
268
+ same = _same_rows(keys, "s", "c")
269
+ db.execute(
270
+ f"DELETE FROM {state.ref} s WHERE EXISTS "
271
+ f"(SELECT 1 FROM __sverify_change c WHERE {same})"
272
+ )
273
+ cols = ", ".join(_q(c) for c in state.schema.names)
274
+ db.execute(
275
+ f"INSERT INTO {state.ref} ({cols}) SELECT {cols} FROM __sverify_merged"
276
+ )
277
+ finally:
278
+ db.unregister("__sverify_change")
279
+ db.unregister("__sverify_merged")
280
+ db.execute("COMMIT")
281
+ except BaseException:
282
+ db.execute("ROLLBACK")
283
+ raise
284
+
285
+ def retire(self, view, column: str, cutoff: object) -> int:
286
+ """`Store.retire` in place: one DELETE in DuckDB."""
287
+ z = view.state
288
+ if not isinstance(z, Resident):
289
+ return super().retire(view, column, cutoff)
290
+ with DuckDBStore._lock:
291
+ if DuckDBStore._db is None:
292
+ DuckDBStore._db = _duckdb.cursor()
293
+ db = DuckDBStore._db
294
+ where = f"{_q(column)} <= ?"
295
+ row = db.execute(
296
+ f"SELECT count(DISTINCT {_q(column)}) FROM {z.ref} WHERE {where}", [cutoff]
297
+ ).fetchone()
298
+ gone = row[0] if row else 0
299
+ db.execute(f"DELETE FROM {z.ref} WHERE {where}", [cutoff])
300
+ return int(gone)
301
+
302
+ def with_keys(self, z: State, columns: Sequence[str], keys: pa.Table) -> State:
303
+ """`Store.with_keys` in DuckDB: a semi-join with NULLs equal."""
304
+ if not isinstance(z, Resident):
305
+ return super().with_keys(z, columns, keys)
306
+ with DuckDBStore._lock:
307
+ if DuckDBStore._db is None:
308
+ DuckDBStore._db = _duckdb.cursor()
309
+ db = DuckDBStore._db
310
+ on = " AND ".join(
311
+ f"s.{_q(c)} IS NOT DISTINCT FROM k.{_q(k)}"
312
+ for c, k in zip(columns, keys.column_names, strict=True)
313
+ )
314
+ db.register("__sverify_keys", keys)
315
+ try:
316
+ return db.sql(
317
+ f"SELECT s.* FROM {z.ref} s WHERE EXISTS "
318
+ f"(SELECT 1 FROM __sverify_keys k WHERE {on})"
319
+ ).to_arrow_table()
320
+ finally:
321
+ db.unregister("__sverify_keys")
322
+
323
+ def has_negative(self, z: State) -> bool:
324
+ if not isinstance(z, Resident):
325
+ return super().has_negative(z)
326
+ db = _duckdb.cursor()
327
+ try:
328
+ row = db.execute(f"SELECT bool_or({_q(WEIGHT)} < 0) FROM {z.ref}").fetchall()[0]
329
+ finally:
330
+ db.close()
331
+ return bool(row and row[0])
332
+
333
+
334
+ # A new process database (`_duckdb.reset`) needs a new cursor.
335
+ _duckdb.on_reset(lambda: setattr(DuckDBStore, "_db", None))
336
+
337
+
338
+ PLUGIN = ProfilePlugin(
339
+ "duckdb",
340
+ title="DuckDB",
341
+ store=DuckDBStore,
342
+ default=True,
343
+ translation="sverify's DuckDB lowering, proved for every plan, and its SQL writer",
344
+ settings=SETTINGS,
345
+ installed_version=_version,
346
+ restore=_restore,
347
+ runner=_run,
348
+ local=True,
349
+ read_settings=_read_settings,
350
+ dialect=_dialect,
351
+ run_tables=_run_tables,
352
+ # The functions only some engines run (#50, #53-#55, #94, #810, #812,
353
+ # #325's black boxes), and the lift's guards (`sverify_raise`: a date of
354
+ # columns outside the calendar, #809).
355
+ functions=frozenset(
356
+ {
357
+ "regexp_extract",
358
+ "regexp_replace",
359
+ "md5",
360
+ "sha256",
361
+ "first",
362
+ "last",
363
+ "string_agg",
364
+ "array_agg",
365
+ "median",
366
+ "quantile_cont",
367
+ "quantile_disc",
368
+ "mode",
369
+ "arg_min",
370
+ "arg_max",
371
+ "covar_samp",
372
+ "covar_pop",
373
+ "corr",
374
+ "sverify_pair",
375
+ "list_prepend",
376
+ "list_concat",
377
+ "list_contains",
378
+ "list_position",
379
+ "flatten",
380
+ "sverify_raise",
381
+ *black_box.NAMES,
382
+ }
383
+ ),
384
+ # The variance over a frame, which only DuckDB's writer computes so far.
385
+ window_functions=frozenset({"variance", "std_dev"}),
386
+ guards=(RANGE_GUARD,),
387
+ )
@@ -0,0 +1,294 @@
1
+ """The DuckDB dialect.
2
+
3
+ DuckDB already raises on BIGINT overflow (`+`, `-`, `*` and negation), divides
4
+ doubles by IEEE 754 rules, has `isnan`, and numbers a table's rows in insertion
5
+ order with `rowid`. Its `=` and `<` on doubles are the model's: NaN equals
6
+ itself and is largest, and -0.0 equals 0.0 (`canon` keeps -0.0 out of
7
+ results). Its `//` truncates BIGINTs
8
+ (and is plain `/` on doubles), so integer division is built from `%`, which
9
+ truncates, and is exact whichever way `//` rounds; `error()` raises where
10
+ DataFusion fails at run time.
11
+
12
+ Strings: `length`, `strpos` and `substring` count code points (DuckDB has
13
+ `*_grapheme` variants for grapheme clusters), and strings compare bytewise
14
+ without a collation. `LIKE` has no escape character by default, so the SQL
15
+ names one. Regular expressions are RE2's, DataFusion's Rust's: they agree on
16
+ the simple patterns of `Text.simpleRegex`, but `\\d`, `\\w` and `\\s` are
17
+ ASCII-only in RE2. `upper`/`lower` map case with utf8proc (black boxes in
18
+ Lean; `'ß'` stays one character, where DataFusion writes `'SS'`). So the SQL
19
+ raises on non-ASCII text where they would differ from DataFusion (#70).
20
+
21
+ Where DuckDB computes a function differently from the reference (doubles'
22
+ NaN and ±inf, the elementary functions outside their domains, division and
23
+ `%` by zero, `MIN % -1`, `<<`, `overflow` = `SILENT` or `SATURATE`), the SQL is
24
+ the generated lowering's template, proved in Lean (`lowered`,
25
+ `sverify.sql.lowering`, `engines/duckdb/facts/` R15).
26
+
27
+ Times: `date_part`'s parts mean what they do in DataFusion (`millisecond`
28
+ and `microsecond` within the minute, `week` ISO, `dow` from Sunday) on the
29
+ proleptic calendar with a year 0. DuckDB's timestamps reach beyond the
30
+ reference's (0001-01-01 to 9999-12-31, D32), so the writer raises outside them
31
+ before `date_part`, truncation or date arithmetic. Adding months clamps to the
32
+ end of the month, as `Time.addMonths` does. The
33
+ timestamp 2⁶³ - 1 µs is DuckDB's `infinity` (and its range starts in 290309
34
+ BC), which `date_trunc` leaves as it is.
35
+ """
36
+
37
+ from collections.abc import Sequence
38
+ from dataclasses import dataclass
39
+
40
+ from sverify.black_box import BlackBox
41
+ from sverify.sql.core import I64_MAX, I64_MIN, Dialect, Kind, Lst
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class DuckDBDialect(Dialect):
46
+ # DuckDB computes decimals exactly (#27): `+`, `-` and `×` at the types the
47
+ # reference gives them, casts rounding half away from zero.
48
+ decimals: bool = True
49
+
50
+ def type_name(self, kind: Kind) -> str:
51
+ return "DOUBLE" if kind == "float" else super().type_name(kind)
52
+
53
+ def interval_lit(self, micros: int) -> str:
54
+ return f"to_microseconds({self.int_lit(micros)})"
55
+
56
+ def is_nan(self, x: str) -> str:
57
+ return f"isnan({x})"
58
+
59
+ def float_eq(self, a: str, b: str) -> str:
60
+ return f"({a} = {b})"
61
+
62
+ def float_lt(self, a: str, b: str) -> str:
63
+ return f"({a} < {b})"
64
+
65
+ def raise_(self, message: str, dep: str, kind: Kind) -> str:
66
+ text = f"concat({self.str_lit(f'sverify: {message}: ')}, CAST({dep} AS VARCHAR))"
67
+ return self.cast(f"error({text})", kind)
68
+
69
+ def trunc_div(self, a: str, b: str) -> str:
70
+ # The dividend minus the remainder divides exactly, however `//` rounds. `%`
71
+ # raises on `MIN % -1`, which is where the quotient overflows.
72
+ return f"(({a} - ({a} % {b})) // {b})"
73
+
74
+ def trunc_mod(self, a: str, b: str) -> str:
75
+ return f"({a} % {b})"
76
+
77
+ def int_product(self, a: str, n: str) -> str:
78
+ return f"list_reduce(list_transform(range({n}), lambda i: {a}), lambda x, y: x * y)"
79
+
80
+ def float_to_int(self, x: str) -> str:
81
+ # The cast raises on NaN, ±inf and values outside 64 bits.
82
+ return f"CAST(trunc({x}) AS BIGINT)"
83
+
84
+ def float_to_int_or_null(self, x: str) -> str:
85
+ # NULL where `float_to_int` raises: NaN (above every number in
86
+ # DuckDB), ±inf and outside [-2⁶³, 2⁶³), where no double lies within
87
+ # 2048 below -2⁶³. A range test, twice as fast as TRY_CAST.
88
+ lo, hi = "-9223372036854775808.0", "9223372036854775808.0"
89
+ return f"(CASE WHEN {x} >= {lo} AND {x} < {hi} THEN CAST(trunc({x}) AS BIGINT) END)"
90
+
91
+ def narrow_or_null(self, x: str, bits: int) -> str:
92
+ lo, hi = self.int_lit(-(2 ** (bits - 1))), self.int_lit(2 ** (bits - 1) - 1)
93
+ return f"(CASE WHEN {x} BETWEEN {lo} AND {hi} THEN {x} END)"
94
+
95
+ def lowered(self, fn: str, args: list[str], kind: Kind) -> str | None:
96
+ # The generated, proved templates (`SubstraitLean/LoweringDuckDB.lean`).
97
+ from sverify.sql import lowering
98
+
99
+ sql = lowering.render(
100
+ fn,
101
+ args,
102
+ lambda message, dep: self.raise_(message, dep, kind),
103
+ self.float_lit,
104
+ self.int_lit,
105
+ self.guards,
106
+ )
107
+ # Wrap-arounds compute in HUGEINT: the result is a BIGINT again.
108
+ return self.cast(sql, "int") if sql is not None and kind == "int" else sql
109
+
110
+ def row_ordinal(self) -> str:
111
+ return "rowid"
112
+
113
+ def int_sum(self, v: str) -> str:
114
+ # SUM of BIGINT is a HUGEINT: exact.
115
+ total = f"SUM({v})"
116
+ fail = self.raise_("integer overflow in SUM", total, "int")
117
+ inside = f"{total} BETWEEN {I64_MIN} AND {I64_MAX}"
118
+ return (
119
+ f"(CASE WHEN {total} IS NULL THEN {self.null('int')} WHEN {inside} "
120
+ f"THEN CAST({total} AS BIGINT) ELSE {fail} END)"
121
+ )
122
+
123
+ def int_avg(self, v: str, over: str) -> str:
124
+ # SUM of BIGINT is a HUGEINT, so the sum is exact; `//` truncates.
125
+ return f"CAST(SUM({v}) {over} // COUNT({v}) {over} AS BIGINT)"
126
+
127
+ def window_int_sum(self, v: str, over: str) -> str:
128
+ # SUM of BIGINT is a HUGEINT: exact.
129
+ total = f"SUM({v}) {over}"
130
+ fail = self.raise_("integer overflow in SUM", total, "int")
131
+ inside = f"{total} BETWEEN {I64_MIN} AND {I64_MAX}"
132
+ return (
133
+ f"(CASE WHEN {total} IS NULL THEN {self.null('int')} WHEN {inside} "
134
+ f"THEN CAST({total} AS BIGINT) ELSE {fail} END)"
135
+ )
136
+
137
+ def float_extreme(self, fn: str, v: str, over: str) -> str:
138
+ # DuckDB orders doubles as the codes do: NaN above `+∞` (#371).
139
+ return f"{fn}({v}) {over}" if over else f"{fn}({v})"
140
+
141
+ def pick(self, fn: str, v: str, order: Sequence[str]) -> str:
142
+ # DuckDB's own `first`/`last` of the non-NULL values: the group's
143
+ # values are not gathered into a list (4x faster on 5M rows, #810).
144
+ return f"{fn}({v} ORDER BY {', '.join(order)}) FILTER (WHERE {v} IS NOT NULL)"
145
+
146
+ def window_pick(self, fn: str, v: str, w: str) -> str:
147
+ return f"{'FIRST' if fn == 'first' else 'LAST'}_VALUE({v} IGNORE NULLS) {w}"
148
+
149
+ def string_agg(self, v: str, sep: str, order: Sequence[str]) -> str:
150
+ return f"string_agg({v}, {sep} ORDER BY {', '.join(order)})"
151
+
152
+ def collect(self, v: str, order: Sequence[str]) -> str:
153
+ return f"list({v} ORDER BY {', '.join(order)}) FILTER (WHERE {v} IS NOT NULL)"
154
+
155
+ def quantile(self, cont: bool, v: str, q: str) -> str:
156
+ # DuckDB reads a decimal fraction exactly (#53). Its interpolation
157
+ # `lo·(1−d) + hi·d` may round past the values: the model keeps it
158
+ # between them, and so does the clamp. Between -inf and +inf it is
159
+ # NaN, which no operation creates (#561): raise where it is NaN and
160
+ # no value is (NaN sorts above every number, so `MAX` is NaN exactly
161
+ # then) (`duckdb-quantile-cont-interpolation`).
162
+ if not cont:
163
+ return f"quantile_disc({v}, {q})"
164
+ qc = f"quantile_cont({v}, {q})"
165
+ value = f"LEAST(GREATEST({qc}, MIN({v})), MAX({v}))"
166
+ if not self.guards:
167
+ return value
168
+ made = f"({self.is_nan(qc)} AND NOT {self.is_nan(f'MAX({v})')})"
169
+ return self.case_when(made, self.raise_("domain error", f"MIN({v})", "float"), value)
170
+
171
+ def mode(self, v: str, order: Sequence[str]) -> str:
172
+ # Its input in this order, DuckDB keeps the value seen first of those
173
+ # that tie (`engines/duckdb/facts/duckdb-mode-ties.json`).
174
+ return f"mode({v} ORDER BY {', '.join(order)})"
175
+
176
+ def unnest_from(self, source: str, lst: str, alias: str) -> str:
177
+ e, i = self.quote("e"), self.quote("i")
178
+ return f"{source}, UNNEST({lst}) WITH ORDINALITY AS {alias}({e}, {i})"
179
+
180
+ def list_lit(self, items: list[str], kind: Lst) -> str:
181
+ if not items:
182
+ return self.cast("[]", kind)
183
+ return self.cast(f"[{', '.join(items)}]", kind)
184
+
185
+ def list_element(self, x: str, offset: int) -> str:
186
+ # DuckDB counts from 1, and from the end (-1 the last) like the model.
187
+ return f"({x})[{offset + 1 if offset >= 0 else offset}]"
188
+
189
+ def cardinality(self, x: str) -> str:
190
+ return f"len({x})"
191
+
192
+ def list_fn(self, name: str, args: list[str]) -> str:
193
+ # DuckDB's own, as the model states them (#810, #812).
194
+ return f"{name}({', '.join(args)})"
195
+
196
+ def pair(self, a: str, b: str) -> str:
197
+ return f"(CASE WHEN {a} IS NULL OR {b} IS NULL THEN NULL ELSE list_value({a}, {b}) END)"
198
+
199
+ def covar(self, fn: str, v: str) -> str:
200
+ return f"{fn.upper()}({v}[1], {v}[2])"
201
+
202
+ def is_ascii(self, s: str) -> str:
203
+ return f"(strlen({s}) = length({s}))"
204
+
205
+ def octet_length(self, s: str) -> str:
206
+ return f"strlen({s})"
207
+
208
+ def like_pattern(self, p: str) -> str:
209
+ odd = f"regexp_matches({p}, {self.str_lit(r'(^|[^\\])(\\\\)*\\$')})"
210
+ return f"(CASE WHEN {odd} THEN {p} || {self.str_lit(chr(92))} ELSE {p} END)"
211
+
212
+ def list_lt(self, a: str, b: str) -> str:
213
+ # DuckDB orders a NULL element above every value; the reference makes
214
+ # the comparison NULL where such an element decides it. `k` is the
215
+ # first position where the elements are distinct (NULL equals NULL).
216
+ k = (
217
+ f"list_position(list_transform(range(1, least(len({a}), len({b})) + 1), "
218
+ f"lambda i: {a}[i] IS DISTINCT FROM {b}[i]), true)"
219
+ )
220
+ return (
221
+ f"(CASE WHEN {a} IS NULL OR {b} IS NULL THEN NULL "
222
+ f"WHEN {k} IS NULL THEN len({a}) < len({b}) "
223
+ f"WHEN {a}[{k}] IS NULL OR {b}[{k}] IS NULL THEN NULL ELSE {a}[{k}] < {b}[{k}] END)"
224
+ )
225
+
226
+ def substring(self, s: str, start: str, length: str | None) -> str:
227
+ return (
228
+ f"substring({s}, {start})" if length is None else f"substring({s}, {start}, {length})"
229
+ )
230
+
231
+ def trim(self, s: str, chars: str, left: bool, right: bool) -> str:
232
+ f = "trim" if left and right else "ltrim" if left else "rtrim"
233
+ return f"{f}({s}, {chars})"
234
+
235
+ def regex_search(self, s: str, pattern: str) -> str:
236
+ return f"regexp_matches({s}, {self.str_lit(pattern)})"
237
+
238
+ def regex_extract(self, s: str, pattern: str, group: int) -> str:
239
+ return f"regexp_extract({s}, {self.str_lit(pattern)}, {group})"
240
+
241
+ def regex_replace(self, s: str, pattern: str, replacement: str, every: bool) -> str:
242
+ flags = ", 'g'" if every else ""
243
+ return f"regexp_replace({s}, {self.str_lit(pattern)}, {self.str_lit(replacement)}{flags})"
244
+
245
+ def black_box(self, row: BlackBox, args: list[str]) -> str:
246
+ # DuckDB's own function: the black box is pinned to it (#325).
247
+ return row.duckdb.format(*args)
248
+
249
+ def black_box_agg(self, row: BlackBox, v: str) -> str:
250
+ return row.duckdb.format(v)
251
+
252
+ def date_part(self, part: str, ts: str) -> str:
253
+ return self.cast(f"date_part({self.str_lit(part)}, {ts})", "int")
254
+
255
+ def day_part(self, part: str, d: str) -> str:
256
+ # A DATE's own parts, which are its midnight's: no cast.
257
+ if part in ("hour", "minute", "second", "millisecond", "microsecond"):
258
+ return super().day_part(part, d)
259
+ return self.cast(f"date_part({self.str_lit(part)}, {d})", "int")
260
+
261
+ def date_trunc(self, unit: str, ts: str) -> str:
262
+ return ts if unit == "microsecond" else f"date_trunc({self.str_lit(unit)}, {ts})"
263
+
264
+ def time_micros(self, ts: str) -> str:
265
+ return f"epoch_us({ts})"
266
+
267
+ def time_add(self, t: str, micros: int) -> str:
268
+ # TIME + INTERVAL wraps around midnight (`duckdb-time-plus-interval`).
269
+ return f"({t} + {self.interval_lit(micros)})"
270
+
271
+ def time_trunc(self, unit: str, t: str) -> str:
272
+ # DuckDB has no `date_trunc` of a TIME: truncate it on 1970-01-01.
273
+ return self.cast(self.date_trunc(unit, f"(DATE '1970-01-01' + {t})"), "tod")
274
+
275
+ def as_time(self, us: str) -> str:
276
+ return f"make_timestamp({us})"
277
+
278
+ def date_time(self, d: str) -> str:
279
+ return f"CAST({d} AS TIMESTAMP)"
280
+
281
+ def epoch_us(self, ts: str) -> str:
282
+ return f"epoch_us({ts})"
283
+
284
+ def date_add_days(self, d: str, n: str) -> str:
285
+ # DATE + INTEGER is a DATE; a count beyond 32 bits leaves chrono's
286
+ # dates anyway (and the cast raises).
287
+ return f"({d} + CAST({n} AS INTEGER))"
288
+
289
+ def add_months(self, x: str, months: int, kind: Kind) -> str:
290
+ # DuckDB clamps to the month's end; DATE + INTERVAL is a TIMESTAMP.
291
+ return self.cast(f"({x} + to_months({self.int_lit(months)}))", kind)
292
+
293
+
294
+ DUCKDB: Dialect = DuckDBDialect("duckdb")
@@ -0,0 +1,163 @@
1
+ """DuckDB as an engine, through SQL generated from the plan.
2
+
3
+ Internal: not part of sverify's public API, which is `sverify`, `sverify.io`,
4
+ `sverify.engines` and `sverify.errors`; it may change in any release.
5
+
6
+ `run` writes the plan as SQL with `sverify.sql.to_sql` (whose semantics are
7
+ Lean's `Rel.eval`, see `sverify.sql.core`) and runs it on an in-process
8
+ DuckDB database holding the given tables. DuckDB's Substrait extension is not
9
+ used.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import json
16
+ import threading
17
+ from collections.abc import Callable, Mapping, Sequence
18
+ from typing import Literal, overload
19
+
20
+ import duckdb
21
+ import pyarrow as pa
22
+
23
+ from sverify import _duckdb
24
+ from sverify._scan import Native, Resident
25
+ from sverify.sql import to_sql
26
+ from sverify_duckdb.dialect import DUCKDB
27
+
28
+
29
+ @functools.lru_cache(maxsize=4096)
30
+ def _sql(plan: str, guards: bool = True, finite: bool = True) -> str:
31
+ """`to_sql` of a JSON plan, memoized: an incremental view runs the same
32
+ delta plans on every batch."""
33
+ return to_sql(json.loads(plan), DUCKDB, guards=guards, finite=finite)
34
+
35
+
36
+ _DB: duckdb.DuckDBPyConnection | None = None
37
+ _LOCK = threading.Lock()
38
+
39
+
40
+ def _forget_cursor() -> None:
41
+ global _DB
42
+ _DB = None
43
+
44
+
45
+ _duckdb.on_reset(_forget_cursor)
46
+
47
+
48
+ def setting(name: str) -> object:
49
+ """The value of DuckDB setting `name` on the engine's cursor, which
50
+ every `run` uses: a session's `SET GLOBAL` shows here, a `SET` on
51
+ another cursor does not."""
52
+ global _DB
53
+ with _LOCK:
54
+ if _DB is None:
55
+ _DB = _duckdb.cursor()
56
+ rows = _DB.execute("SELECT current_setting(?)", [name]).fetchall()
57
+ return rows[0][0] if rows else None
58
+
59
+
60
+ def settings(names: Sequence[str]) -> dict[str, object]:
61
+ """The values of DuckDB settings `names` on the engine's cursor, as
62
+ `setting` reads each, in one query."""
63
+ if not names:
64
+ return {}
65
+ global _DB
66
+ with _LOCK:
67
+ if _DB is None:
68
+ _DB = _duckdb.cursor()
69
+ sql = "SELECT " + ", ".join(["current_setting(?)"] * len(names))
70
+ (row,) = _DB.execute(sql, list(names)).fetchall()
71
+ return dict(zip(names, row, strict=True))
72
+
73
+
74
+ @overload
75
+ def run(
76
+ plan: str | dict,
77
+ tables: Mapping[str, pa.Table | Native],
78
+ *,
79
+ guards: bool = True,
80
+ keep: Literal[False] = False,
81
+ finite: bool = True,
82
+ ) -> pa.Table: ...
83
+
84
+
85
+ @overload
86
+ def run(
87
+ plan: str | dict,
88
+ tables: Mapping[str, pa.Table | Native],
89
+ *,
90
+ guards: bool = True,
91
+ keep: Literal[True],
92
+ finite: bool = True,
93
+ ) -> Resident: ...
94
+
95
+
96
+ def run(
97
+ plan: str | dict,
98
+ tables: Mapping[str, pa.Table | Native],
99
+ *,
100
+ guards: bool = True,
101
+ keep: bool = False,
102
+ finite: bool = True,
103
+ ) -> pa.Table | Resident:
104
+ """Run a Substrait JSON plan on DuckDB over `tables`: Arrow tables, or
105
+ tables DuckDB reads where they are (`sverify._scan.Native`: Parquet
106
+ files, or tables it holds). With `keep`, the result stays in DuckDB, as
107
+ a `Resident` table.
108
+
109
+ The process's database serves every call (`sverify._duckdb`; opening
110
+ one costs ~10 ms), through a cursor of the engine's own; the tables are
111
+ created for the call, as temporary tables, and dropped after it.
112
+ `guards=False`, `finite=False`: see `sverify.sql.to_sql`."""
113
+ global _DB
114
+ sql = (
115
+ _sql(plan, guards, finite)
116
+ if isinstance(plan, str)
117
+ else to_sql(plan, DUCKDB, guards=guards, finite=finite)
118
+ )
119
+ # `to_sql` numbers a table's rows with `rowid` where the plan needs their order.
120
+ ordered = DUCKDB.row_ordinal() in sql
121
+ with _LOCK:
122
+ if _DB is None:
123
+ _DB = _duckdb.cursor()
124
+ db = _DB
125
+ _duckdb.collect(db)
126
+ drops: list[Callable[[], None]] = []
127
+ try:
128
+ for name, table in tables.items():
129
+ if isinstance(table, Native):
130
+ # A view reads the table where it is; a table holds its
131
+ # rows in order when the plan needs `rowid`.
132
+ drops.append(table.attach(db, name, table=ordered))
133
+ continue
134
+ if not ordered:
135
+ # A view of the Arrow data, without copying it.
136
+ db.register(name, table)
137
+ drops.append(functools.partial(_unregister, db, name))
138
+ continue
139
+ # A real table (not a view on the Arrow data): `rowid` numbers its
140
+ # rows in insertion order, which `to_sql` uses as the scan order.
141
+ db.register("__sverify_input", table)
142
+ db.execute(
143
+ f"CREATE TEMP TABLE {DUCKDB.quote(name)} AS SELECT * FROM __sverify_input"
144
+ )
145
+ db.unregister("__sverify_input")
146
+ drops.append(functools.partial(_drop, db, name))
147
+ if not keep:
148
+ return db.sql(sql).to_arrow_table()
149
+ name = Resident.new_name()
150
+ db.execute(f"CREATE TABLE main.{DUCKDB.quote(name)} AS {sql}")
151
+ schema = db.sql(f"SELECT * FROM main.{DUCKDB.quote(name)} LIMIT 0").to_arrow_table()
152
+ return Resident(name, schema.schema)
153
+ finally:
154
+ for drop in drops:
155
+ drop()
156
+
157
+
158
+ def _unregister(db: duckdb.DuckDBPyConnection, name: str) -> None:
159
+ db.unregister(name)
160
+
161
+
162
+ def _drop(db: duckdb.DuckDBPyConnection, name: str) -> None:
163
+ db.execute(f"DROP TABLE IF EXISTS {DUCKDB.quote(name)}")
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.5
2
+ Name: sverify-duckdb
3
+ Version: 0.8.0
4
+ Summary: DuckDB as an engine of sverify: plans verified in Lean, written as DuckDB SQL
5
+ Project-URL: Source, https://github.com/AlexanderNenninger/substrait-lean/tree/main/engines/duckdb
6
+ Project-URL: Issues, https://github.com/AlexanderNenninger/substrait-lean/issues
7
+ License-Expression: MPL-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: sverify==0.8.0
11
+ Provides-Extra: run
12
+ Requires-Dist: duckdb>=2.0.0; extra == 'run'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # sverify-duckdb
16
+
17
+ Sverify-duckdb is a working prototype, and so is sverify, which it extends.
18
+ Their proofs and code still need a human audit before anyone relies on their
19
+ results.
20
+
21
+ DuckDB as an engine of [sverify](https://github.com/AlexanderNenninger/substrait-lean),
22
+ its default one: a plan verified in Lean is written as DuckDB SQL through a
23
+ lowering proved for every plan, and runs on the process's DuckDB database.
24
+ `pip install sverify` installs it with DuckDB (`sverify-duckdb[run]`): for now
25
+ sverify's table store runs on DuckDB, so the base needs it. sverify finds it
26
+ through its `ProfilePlugin` in the entry-point group `sverify.profiles`.
27
+
28
+ The directory is one engine package of #1189:
29
+
30
+ - `src/sverify_duckdb/`: the plugin (`PLUGIN`) with the table store
31
+ (`DuckDBStore`), the dialect (`dialect`: `DUCKDB`) and the runner (`engine`);
32
+ - `facts/`: what DuckDB does at each of the core's options, the evidence for
33
+ `Profile.duckdb` ([facts/README.md](facts/README.md));
34
+ - `replay/`: the replay of DuckDB's sqllogictests, one ledger per area, the
35
+ fuzz findings and the probes the facts cite;
36
+ - `tests/`: its tests, which run in sverify's test session
37
+ (`python/pyproject.toml`'s `testpaths`).
38
+
39
+ Its Lean half (the profile, the generated lowering and the lift, `Sverify.DuckDB`)
40
+ follows.
@@ -0,0 +1,8 @@
1
+ sverify_duckdb/__init__.py,sha256=KqVuu2lucfRZi87UN3FRTiftPm_n3pIPl3HYjKOKt1Y,13690
2
+ sverify_duckdb/dialect.py,sha256=gNScpZETBdbY8CbhD8PqaLIMO57GNhcJl9_O7HmzRoc,13174
3
+ sverify_duckdb/engine.py,sha256=L9dIt_ZpnFkzHR6RBRzRv9WgP44kfZ7spEjXXJTBmEo,5413
4
+ sverify_duckdb-0.8.0.dist-info/METADATA,sha256=1DlK1yZiPOyeIf6iQa0-w8dpu_SsAOiIpiNCYDsNBYY,1832
5
+ sverify_duckdb-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ sverify_duckdb-0.8.0.dist-info/entry_points.txt,sha256=pIDggOEu2sMEaPUfy2Wp8kARGuRpvVrD8O9yFJfEIZA,50
7
+ sverify_duckdb-0.8.0.dist-info/licenses/LICENSE,sha256=Pz2eACSxkhsGfW9_iN60pgy-enjnbGTj8df8O3ebnQQ,16726
8
+ sverify_duckdb-0.8.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [sverify.profiles]
2
+ duckdb = sverify_duckdb:PLUGIN
@@ -0,0 +1,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code Form License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code Form is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code Form is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.