sverify-spark 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,186 @@
1
+ """sverify's Spark engine (#1189): the Spark SQL dialect
2
+ (`sverify_spark.dialect`: `SPARK`, `SPARK_CONF`), with shims where Spark
3
+ differs from the reference, proved against Spark's facts (`Rel.spark_sound`),
4
+ and the runner on a Spark session (`sverify_spark.engine`), registered as the
5
+ `ProfilePlugin` `PLUGIN` under the entry-point group `sverify.profiles`.
6
+
7
+ Spark's settings: a run reads the session's `spark.conf`: sverify's local
8
+ session (`sverify_spark.engine.session`, which starts with `SPARK_CONF`) or
9
+ the session passed as the engine. The facts were probed under ANSI mode,
10
+ with `TIMESTAMP` as `TIMESTAMP_NTZ` and the session time zone UTC
11
+ (spark-exec-settings); the writer's SQL relies on those and on
12
+ `caseSensitive` and `escapedStringLiterals`, so a session that changes them
13
+ refuses every run. The legacy statistics, decimal-precision and
14
+ `percentile_disc` settings refuse only plans whose options they change.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import sys
21
+ from collections.abc import Mapping, Sequence
22
+ from typing import Any
23
+
24
+ from sverify._unsupported import ISSUE_271, RANGE_GUARD
25
+ from sverify.profiles import ProfilePlugin, Setting
26
+ from sverify_spark.store import ArrowStore
27
+
28
+ #: The settings Spark's profile assumes.
29
+ SETTINGS: tuple[Setting, ...] = (
30
+ Setting(
31
+ "spark.sql.ansi.enabled",
32
+ (True,),
33
+ "refuse",
34
+ ("spark-exec-settings", "spark-int-arith", "spark-int-divide", "spark-double-divide"),
35
+ "whether integer overflow, a zero divisor and a bad cast raise or give NULL or a "
36
+ "wrapped value (overflow, on_division_by_zero, cast_failure)",
37
+ ),
38
+ Setting(
39
+ "spark.sql.timestampType",
40
+ ("timestamp_ntz",),
41
+ "refuse",
42
+ ("spark-time-zones", "spark-type-names"),
43
+ "what TIMESTAMP means: an instant in the session time zone or a wall-clock time",
44
+ ),
45
+ Setting(
46
+ "spark.sql.session.timeZone",
47
+ ("utc", "etc/utc"),
48
+ "refuse",
49
+ ("spark-time-zones",),
50
+ "the wall clock the written SQL reads microseconds as (`unix_micros`, `timestamp_micros`)",
51
+ ),
52
+ Setting(
53
+ "spark.sql.caseSensitive",
54
+ (True,),
55
+ "refuse",
56
+ ("spark-exec-settings",),
57
+ "whether columns `a` and `A` are one column",
58
+ ),
59
+ Setting(
60
+ "spark.sql.parser.escapedStringLiterals",
61
+ (False,),
62
+ "refuse",
63
+ ("spark-exec-settings",),
64
+ "how a backslash in a string literal reads",
65
+ ),
66
+ Setting(
67
+ "spark.sql.legacy.statisticalAggregate",
68
+ (False,),
69
+ "refuse",
70
+ ("spark-var-stddev", "spark-covar", "spark-corr"),
71
+ "whether a sample variance, covariance or correlation of one value is NULL or NaN "
72
+ "(stat_degenerate)",
73
+ ("stat_degenerate", "stat_algo"),
74
+ ),
75
+ Setting(
76
+ "spark.sql.decimalOperations.allowPrecisionLoss",
77
+ (True,),
78
+ "refuse",
79
+ ("spark-decimal-arith",),
80
+ "the scale of a decimal result past 38 digits (decimal_rescale)",
81
+ ("decimal_rescale",),
82
+ ),
83
+ Setting(
84
+ "spark.sql.legacy.percentileDiscCalculation",
85
+ (False,),
86
+ "refuse",
87
+ ("spark-quantile",),
88
+ "which value percentile_disc takes (quantile_interp)",
89
+ ("quantile_interp",),
90
+ ),
91
+ )
92
+
93
+ #: Spark 4.3.0's defaults for the settings `SETTINGS` reads (spark-exec-settings).
94
+ DEFAULTS: Mapping[str, str] = {
95
+ "spark.sql.ansi.enabled": "true",
96
+ "spark.sql.timestampType": "TIMESTAMP_LTZ",
97
+ "spark.sql.caseSensitive": "false",
98
+ "spark.sql.parser.escapedStringLiterals": "false",
99
+ "spark.sql.legacy.statisticalAggregate": "false",
100
+ "spark.sql.decimalOperations.allowPrecisionLoss": "true",
101
+ "spark.sql.legacy.percentileDiscCalculation": "false",
102
+ }
103
+
104
+
105
+ def _run(
106
+ con: Any, plan_json: str, session: Any, *, keep: bool, finite: bool, tie_free: bool
107
+ ) -> Any:
108
+ from sverify.engine import _rename_tables, read_tables
109
+ from sverify_spark import engine as spark_engine
110
+
111
+ plan = json.loads(plan_json)
112
+ # Spark's temporary views take plain names, not the delta plans' `t$delta`.
113
+ names = {t: f"__sverify_{i}" for i, t in enumerate(read_tables(plan))}
114
+ _rename_tables(plan, names)
115
+ tables = {alias: con._arrow[t] for t, alias in names.items()}
116
+ return spark_engine.run(plan, tables, session, deterministic=tie_free, finite=finite)
117
+
118
+
119
+ def _is_session(obj: Any) -> bool:
120
+ """A Spark session (any object that is not an engine's name was one,
121
+ before engines were plugins; a session's class is pyspark's)."""
122
+ return type(obj).__module__.startswith("pyspark.")
123
+
124
+
125
+ def _version() -> str | None:
126
+ import pyspark
127
+
128
+ return pyspark.__version__
129
+
130
+
131
+ def _local_session() -> Any:
132
+ """The session a run on `"spark"` uses: sverify's local one, if it has
133
+ started (`sverify_spark.engine.session`); None before, when the run
134
+ starts it with `SPARK_CONF`."""
135
+ engine = sys.modules.get("sverify_spark.engine")
136
+ if engine is None or engine.session.cache_info().currsize == 0:
137
+ return None
138
+ return engine.session()
139
+
140
+
141
+ def _read_settings(names: Sequence[str], session: Any) -> dict[str, Any]:
142
+ spark = session if session is not None else _local_session()
143
+ if spark is None:
144
+ return {}
145
+ return {n: spark.conf.get(n, DEFAULTS.get(n)) for n in names}
146
+
147
+
148
+ def _restore(setting: Setting) -> str:
149
+ from sverify_spark.dialect import SPARK_CONF
150
+
151
+ v = SPARK_CONF.get(setting.name, DEFAULTS.get(setting.name, setting.expected[0]))
152
+ return f'spark.conf.set("{setting.name}", "{v}")'
153
+
154
+
155
+ def _dialect() -> Any:
156
+ from sverify_spark.dialect import SPARK
157
+
158
+ return SPARK
159
+
160
+
161
+ PLUGIN = ProfilePlugin(
162
+ "spark",
163
+ store=ArrowStore,
164
+ title="Spark",
165
+ profile=True,
166
+ translation="sverify's Spark SQL writer, with shims where Spark differs from the "
167
+ "reference, proved against Spark's facts (Rel.spark_sound) and tested against "
168
+ "the reference",
169
+ settings=SETTINGS,
170
+ installed_version=_version,
171
+ restore=_restore,
172
+ runner=_run,
173
+ session=_is_session,
174
+ modules=("pyspark",),
175
+ read_settings=_read_settings,
176
+ dialect=_dialect,
177
+ refuses={
178
+ "sverify_raise": (
179
+ "Spark's SQL of the date guards exhausts its JVM's heap (a date from columns "
180
+ "is 38 KB of nested CASEs)",
181
+ ISSUE_271,
182
+ )
183
+ },
184
+ guards=(RANGE_GUARD,),
185
+ shim_text={"null_order": "NULLs sorted as the reference sorts them"},
186
+ )
@@ -0,0 +1,408 @@
1
+ """Apache Spark SQL (and Databricks SQL) with the Lean model's semantics.
2
+
3
+ Targets Spark 4 with the session configuration of `SPARK_CONF`, above all
4
+ ANSI mode: without it integer overflow wraps around and a bad cast is NULL,
5
+ where the Lean model (and this SQL) raises. Every hook either emits SQL whose
6
+ result is the Lean value, checked on a local Spark session by
7
+ `engines/spark/tests/test_sql_spark.py`, or raises `Unsupported`. The divergences:
8
+
9
+ * **Integers** are `BIGINT`. In ANSI mode `+`, `-`, `*`, negation and
10
+ `MIN div -1` raise on overflow. `/` returns a double, so integer division
11
+ is `div`, which truncates; `%` has the sign of the dividend. A literal
12
+ without a cast is an `INT` (or a `DECIMAL` beyond 64 bits), so every
13
+ integer constant is cast. `SUM` of `BIGINT` raises as soon as a partial
14
+ sum overflows, though Lean's is the true total: it adds `DECIMAL(38,0)`
15
+ values instead (exact) and checks the total against 64 bits.
16
+ * **Doubles** are IEEE, but in ANSI mode `/` raises on a zero divisor, so
17
+ `x / 0.0` is spelled out (±inf by the sign of `x`, or NaN).
18
+ `CAST(x AS BIGINT)` truncates, raises on NaN and ±inf, but saturates at
19
+ 2⁶³: the range is checked first. `FLOOR` and `CEIL` return `BIGINT`, so
20
+ they keep NaN, ±inf and large values as they are. `POWER` is Java's
21
+ `Math.pow`, which is only within 1 ulp, so double powers are refused.
22
+ * **Zero and NaN**: `=` and `<` are the model's: NaN equals itself and is
23
+ largest, and -0.0 equals 0.0. `GROUP BY`, `DISTINCT` and window
24
+ partitions treat them the same way (`NormalizeFloatingNumbers`), and
25
+ `canon` keeps -0.0 out of results.
26
+ * **NULL order**: `NULLS FIRST` is the default for ascending sorts; every
27
+ key says where NULLs go.
28
+ * **Timestamps** are `TIMESTAMP_NTZ`: wall-clock microseconds like Lean.
29
+ Plain `TIMESTAMP` is `TIMESTAMP_LTZ` (by `spark.sql.timestampType`), whose
30
+ calendar fields follow the session time zone, and `date_trunc` returns
31
+ one, so truncation is computed on `TIMESTAMP_NTZ` and `DATE` values
32
+ instead and never touches the time zone. Intervals are `INTERVAL DAY TO
33
+ SECOND`, microseconds like Lean. `extract(SECOND …)` is a decimal with the
34
+ microseconds; `WEEK` is ISO, and `dayofweek` counts from Sunday = 1. Spark
35
+ holds timestamps beyond the reference's (years 0 and +10000), so the
36
+ writer raises outside 0001-01-01 to 9999-12-31 before `date_part` (D32).
37
+ * **Strings**: string literals take backslash escapes (with
38
+ `spark.sql.parser.escapedStringLiterals` off), so backslashes are
39
+ doubled. Strings compare by UTF-8 bytes under the default collation
40
+ `UTF8_BINARY`, which is Lean's code point order; a column with another
41
+ collation (`UTF8_LCASE`, ICU) would compare differently. `length`,
42
+ `locate` and `substring` count characters. Regular expressions are
43
+ Java's, which agree with Rust's on simple patterns (black boxes in Lean);
44
+ `RLIKE` searches. `upper`, `lower` and patterns with `\\d`, `\\w` or
45
+ `\\s` raise on non-ASCII text, where Java's tables differ from Rust's (#70).
46
+ * **Decimals** (#27) follow the reference's types, which are Spark's own
47
+ (`DecimalPrecision`) up to 38 digits; past them Spark cuts the scale to no
48
+ less than 6 (`spark.sql.decimalOperations.allowPrecisionLoss`), so a sum
49
+ or product whose type would pass 38 digits at a scale above 6 is refused.
50
+ A smaller scale rounds half away from zero (`ROUND_HALF_UP`), as the
51
+ reference does. `-x` rounds past 34 significant digits (SP-1), so a
52
+ negation of more than 34 digits is `0 - x`, exact up to scale 6 at 38
53
+ digits, and refused past it. A double goes to a decimal as
54
+ `round(x · 10ˢ)` in doubles, through `BIGINT`, since Spark reads a double
55
+ as its shortest text. Division by an integer (an `AVG`) is refused.
56
+ * **Rows**: tables (Parquet, Delta, views) have no row order, so nothing
57
+ can stand for Lean's list order, which FETCH and ties in a sort or window
58
+ follow: `row_ordinal` is refused. Windows and sorts run with
59
+ `to_sql(..., deterministic=True)`, when the caller knows there are no ties.
60
+ A `SUM` or `AVG` of doubles is Spark's own, within the plan's bound of the
61
+ reference's correctly rounded sum (D25, `float_sum`).
62
+ * **Identifiers** are quoted with backticks; `spark.sql.caseSensitive` keeps
63
+ `a` and `A` apart.
64
+ """
65
+
66
+ from __future__ import annotations
67
+
68
+ import math
69
+ import re
70
+ from collections.abc import Sequence
71
+ from dataclasses import dataclass
72
+
73
+ from sverify.sql.core import I64_MAX, I64_MIN, Dec, Dialect, Kind, Unsupported, _timestamp_text
74
+
75
+ #: Session settings the SQL relies on; `SparkSession.builder.config` each.
76
+ SPARK_CONF: dict[str, str] = {
77
+ # Overflow, division by zero and bad casts raise instead of wrapping or
78
+ # giving NULL.
79
+ "spark.sql.ansi.enabled": "true",
80
+ # Only LTZ values (none here) depend on it; pinned so nothing does.
81
+ "spark.sql.session.timeZone": "UTC",
82
+ "spark.sql.timestampType": "TIMESTAMP_NTZ",
83
+ "spark.sql.caseSensitive": "true",
84
+ # Backslash escapes in string literals, as `str_lit` writes them.
85
+ "spark.sql.parser.escapedStringLiterals": "false",
86
+ }
87
+
88
+ _TYPES: dict[str, str] = {
89
+ "int": "BIGINT",
90
+ "float": "DOUBLE",
91
+ "time": "TIMESTAMP_NTZ",
92
+ "date": "DATE",
93
+ "interval": "INTERVAL DAY TO SECOND",
94
+ "str": "STRING",
95
+ "bool": "BOOLEAN",
96
+ }
97
+
98
+
99
+ def _digits(k: Kind) -> tuple[int, int]:
100
+ """The precision and scale Spark gives an operand of kind `k` in decimal
101
+ arithmetic: a `BIGINT` is a `DECIMAL(20, 0)`."""
102
+ if isinstance(k, Dec):
103
+ return k.p, k.s
104
+ if k == "int":
105
+ return 20, 0
106
+ raise Unsupported(f"decimal arithmetic with a {k} operand on Spark")
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class SparkDialect(Dialect):
111
+ # Decimals (#27), as the module's docstring says.
112
+ decimals: bool = True
113
+
114
+ def quote(self, ident: str) -> str:
115
+ return "`" + ident.replace("`", "``") + "`"
116
+
117
+ def type_name(self, kind: Kind) -> str:
118
+ if isinstance(kind, Dec):
119
+ return super().type_name(kind)
120
+ if kind not in _TYPES:
121
+ raise self.to_duckdb(f"spark has no {kind} type (TIME needs Spark 4.1)")
122
+ return _TYPES[kind]
123
+
124
+ def time_of_day_lit(self, micros: int) -> str:
125
+ raise self.to_duckdb("spark has no tod type (TIME needs Spark 4.1)")
126
+
127
+ def raise_(self, message: str, dep: str, kind: Kind) -> str:
128
+ text = f"concat({self.str_lit(f'sverify: {message}: ')}, CAST({dep} AS STRING))"
129
+ fail = self.cast(f"raise_error({text})", kind)
130
+ return f"(CASE WHEN {dep} IS NULL THEN {self.null(kind)} ELSE {fail} END)"
131
+
132
+ # Literals
133
+
134
+ def str_lit(self, s: str) -> str:
135
+ s = s.replace("\\", "\\\\").replace("'", "\\'")
136
+ # Control characters as escapes, so every query is one line of text.
137
+ return "'" + "".join(f"\\u{ord(c):04x}" if ord(c) < 32 else c for c in s) + "'"
138
+
139
+ def timestamp_lit(self, micros: int) -> str:
140
+ return f"TIMESTAMP_NTZ '{_timestamp_text(micros)}'"
141
+
142
+ # Integers: ANSI mode raises on BIGINT overflow.
143
+
144
+ def trunc_div(self, a: str, b: str) -> str:
145
+ return f"({a} div {b})"
146
+
147
+ def trunc_mod(self, a: str, b: str) -> str:
148
+ return f"({a} % {b})"
149
+
150
+ def int_product(self, a: str, n: str) -> str:
151
+ # Partial products grow in magnitude, so the checked `*` raises
152
+ # exactly when the result leaves 64 bits.
153
+ reps = f"array_repeat({a}, CAST({n} AS INT))"
154
+ return f"aggregate({reps}, {self.int_lit(1)}, (acc, e) -> acc * e)"
155
+
156
+ # Doubles
157
+
158
+ def float_div(self, a: str, b: str) -> str:
159
+ if (c := _float_const(b)) is not None and c != 0:
160
+ return f"({a} / {b})"
161
+ nan, inf, ninf = (self.float_lit(x) for x in (math.nan, math.inf, -math.inf))
162
+ # The divisor is the one zero, +0.0.
163
+ by_zero = (
164
+ f"(CASE WHEN {a} IS NULL THEN {self.null('float')} "
165
+ f"WHEN isnan({a}) OR {a} = 0 THEN {nan} WHEN {a} > 0 THEN {inf} ELSE {ninf} END)"
166
+ )
167
+ return f"(CASE WHEN {b} = 0 THEN {by_zero} ELSE {a} / {b} END)"
168
+
169
+ def whole(self, fn: str, x: str) -> str:
170
+ """`fn` (FLOOR or CEIL, which return BIGINT) on a double. Doubles of
171
+ magnitude 2⁵² and more are whole already; NaN and ±inf stay."""
172
+ big = self.float_lit(2.0**52)
173
+ value = f"CAST({fn}({x}) AS DOUBLE)"
174
+ return f"(CASE WHEN isnan({x}) OR abs({x}) >= {big} THEN {x} ELSE {value} END)"
175
+
176
+ def float_floor(self, x: str) -> str:
177
+ return self.whole("FLOOR", x)
178
+
179
+ def float_ceil(self, x: str) -> str:
180
+ return self.whole("CEIL", x)
181
+
182
+ def float_round(self, x: str) -> str:
183
+ # Half away from zero on the shortest decimal of the double, which is
184
+ # the double's own rounding (a halfway double prints as one).
185
+ return f"ROUND({x})"
186
+
187
+ def float_logb(self, x: str, b: str) -> str:
188
+ raise self.to_duckdb(
189
+ "Spark's LN is Java's StrictMath, not the C libm the Lean model uses "
190
+ "(spark-elem-rounding)"
191
+ )
192
+
193
+ def float_pow(self, a: str, b: str) -> str:
194
+ raise self.to_duckdb(
195
+ "Spark's POWER is Java's Math.pow, within 1 ulp of the C pow the Lean model uses "
196
+ "(spark-elem-rounding)"
197
+ )
198
+
199
+ def float_to_int(self, x: str) -> str:
200
+ # The cast raises on NaN and ±inf but saturates at 2⁶³: check first.
201
+ lo, hi = self.float_lit(-(2.0**63)), self.float_lit(2.0**63)
202
+ fail = self.raise_("CAST to BIGINT out of range", x, "int")
203
+ return f"(CASE WHEN {x} >= {lo} AND {x} < {hi} THEN CAST({x} AS BIGINT) ELSE {fail} END)"
204
+
205
+ def is_nan(self, x: str) -> str:
206
+ return f"isnan({x})"
207
+
208
+ def float_eq(self, a: str, b: str) -> str:
209
+ return f"({a} = {b})"
210
+
211
+ def float_lt(self, a: str, b: str) -> str:
212
+ return f"({a} < {b})"
213
+
214
+ # Temporal
215
+
216
+ def date_part(self, part: str, ts: str) -> str:
217
+ sec = f"extract(SECOND FROM {ts})"
218
+ value = {
219
+ "week": f"extract(WEEK FROM {ts})",
220
+ "dow": f"(dayofweek({ts}) - 1)",
221
+ "doy": f"dayofyear({ts})",
222
+ "second": f"CAST(FLOOR({sec}) AS BIGINT)",
223
+ "millisecond": f"CAST(FLOOR({sec} * 1000) AS BIGINT)",
224
+ "microsecond": f"CAST({sec} * 1000000 AS BIGINT)",
225
+ }.get(part, f"{part}({ts})")
226
+ return self.cast(value, "int")
227
+
228
+ def date_trunc(self, unit: str, ts: str) -> str:
229
+ # `date_trunc` returns TIMESTAMP_LTZ; these stay in NTZ and DATE.
230
+ sec = f"extract(SECOND FROM {ts})"
231
+ day = f"CAST({ts} AS DATE)"
232
+ match unit:
233
+ case "microsecond":
234
+ return ts
235
+ case "millisecond":
236
+ return f"({ts} - make_dt_interval(0, 0, 0, {sec} - FLOOR({sec} * 1000) / 1000))"
237
+ case "second":
238
+ return f"({ts} - make_dt_interval(0, 0, 0, {sec} - FLOOR({sec})))"
239
+ case "minute":
240
+ return f"({ts} - make_dt_interval(0, 0, 0, {sec}))"
241
+ case "hour":
242
+ return f"({ts} - make_dt_interval(0, 0, minute({ts}), {sec}))"
243
+ case "day":
244
+ return f"CAST({day} AS TIMESTAMP_NTZ)"
245
+ case "week":
246
+ # dayofweek: Sunday 1, Monday 2.
247
+ return f"CAST(date_sub({day}, (dayofweek({ts}) + 5) % 7) AS TIMESTAMP_NTZ)"
248
+ return f"CAST(trunc({day}, {self.str_lit(unit.upper())}) AS TIMESTAMP_NTZ)"
249
+
250
+ def date_days(self, d: str) -> str:
251
+ return f"CAST(unix_date({d}) AS BIGINT)"
252
+
253
+ def date_add_days(self, d: str, n: str) -> str:
254
+ return f"date_add({d}, CAST({n} AS INT))"
255
+
256
+ def add_months(self, x: str, months: int, kind: Kind) -> str:
257
+ # `add_months` clamps to the end of a shorter month, as
258
+ # `Time.addMonths` (since Spark 3.0 also from a month's last day).
259
+ if kind == "time":
260
+ return f"({x} + make_ym_interval(0, {months}))"
261
+ return f"add_months({x}, {months})"
262
+
263
+ def as_time(self, us: str) -> str:
264
+ # The session time zone is UTC, so the NTZ cast keeps the instant's clock.
265
+ return f"CAST(timestamp_micros({us}) AS TIMESTAMP_NTZ)"
266
+
267
+ def time_micros(self, ts: str) -> str:
268
+ # The session time zone is UTC, so the LTZ cast keeps the wall clock.
269
+ return f"unix_micros(CAST({ts} AS TIMESTAMP_LTZ))"
270
+
271
+ # Aggregates
272
+
273
+ def int_sum(self, v: str) -> str:
274
+ total = f"SUM(CAST({v} AS DECIMAL(38,0)))"
275
+ fail = self.raise_("integer overflow in SUM", total, "int")
276
+ inside = f"{total} BETWEEN {I64_MIN} AND {I64_MAX}"
277
+ return f"(CASE WHEN {inside} THEN CAST({total} AS BIGINT) ELSE {fail} END)"
278
+
279
+ def int_avg(self, v: str, over: str) -> str:
280
+ # An exact DECIMAL(38,0) sum; `div` truncates toward zero.
281
+ total = f"SUM(CAST({v} AS DECIMAL(38,0))) {over}"
282
+ return f"CAST({total} div COUNT({v}) {over} AS BIGINT)"
283
+
284
+ def window_int_sum(self, v: str, over: str) -> str:
285
+ total = f"SUM(CAST({v} AS DECIMAL(38,0))) {over}"
286
+ fail = self.raise_("integer overflow in SUM", total, "int")
287
+ inside = f"{total} BETWEEN {I64_MIN} AND {I64_MAX}"
288
+ return f"(CASE WHEN {inside} THEN CAST({total} AS BIGINT) ELSE {fail} END)"
289
+
290
+ def day_interval(self, days: int) -> str:
291
+ return f"INTERVAL {days} DAYS"
292
+
293
+ # Decimals
294
+
295
+ def decimal_arith(
296
+ self, op: str, a: str, b: str, sa: int, k: Dec, kinds: tuple[Kind, Kind] | None = None
297
+ ) -> str:
298
+ if kinds is None:
299
+ raise Unsupported(f"decimal {op} of operands of unknown types on Spark")
300
+ (p1, s1), (p2, s2) = (_digits(x) for x in kinds)
301
+ if op == "*":
302
+ p, sc = p1 + p2 + 1, s1 + s2
303
+ else:
304
+ sc = max(s1, s2)
305
+ p = max(p1 - s1, p2 - s2) + sc + 1
306
+ if p > 38 and sc > 6:
307
+ # spark-decimal-arith: Spark cuts the scale to fit 38 digits.
308
+ raise Unsupported(
309
+ f"decimal {op} of DECIMAL({p1}, {s1}) and DECIMAL({p2}, {s2}) on Spark: "
310
+ f"its type DECIMAL({p}, {sc}) has more than 38 digits, and Spark rounds it "
311
+ "to fewer decimal places; cast an operand to fewer digits"
312
+ )
313
+ return self.cast(f"({a} {op} {b})", k)
314
+
315
+ def decimal_neg(self, a: str, k: Dec | None = None) -> str:
316
+ # SP-1: `-x` rounds past 34 significant digits. `0 - x` is exact where
317
+ # its type keeps the scale: up to 37 digits, or 38 at scale 6 or less.
318
+ if k is not None and k.p <= 34:
319
+ return f"(-{a})"
320
+ if k is not None and (k.p <= 37 or k.s <= 6):
321
+ return self.cast(f"({self.decimal_lit(0, Dec(1, 0))} - {a})", k)
322
+ raise self.to_duckdb(
323
+ f"negation of a DECIMAL({k.p if k else '?'}, {k.s if k else '?'}) on Spark: "
324
+ "Spark rounds -x past 34 digits and 0 - x past scale 6 at 38 digits (SP-1)",
325
+ "see #27",
326
+ "cast it to 34 digits or fewer",
327
+ )
328
+
329
+ def decimal_abs(self, a: str, k: Dec | None = None) -> str:
330
+ # SP-1: `abs` negates a negative value as `-x` does.
331
+ return f"(CASE WHEN {a} < 0 THEN {self.decimal_neg(a, k)} ELSE {a} END)"
332
+
333
+ def decimal_cast(self, a: str, k: Dec, src: Kind | None = None) -> str:
334
+ if src != "float":
335
+ return self.cast(a, k)
336
+ if k.p > 18:
337
+ raise self.to_duckdb(
338
+ f"CAST of a double to DECIMAL({k.p}, {k.s}) on Spark: Spark reads the "
339
+ "double as its shortest text, which past 18 digits is not its value",
340
+ "see #27",
341
+ "cast to 18 digits or fewer",
342
+ )
343
+ # `round(x · 10ˢ)` in doubles, halves away from zero (Spark's `ROUND` of
344
+ # a double rounds its shortest text, which keeps every half where it
345
+ # is); whole doubles below 2⁶³ are exact as `BIGINT`s.
346
+ scale = self.float_lit(float(10**k.s))
347
+ units = self.cast(f"CAST(ROUND({a} * {scale}) AS BIGINT)", Dec(k.p, 0))
348
+ return self.cast(f"({units} * {self.decimal_lit(1, Dec(k.s + 1, k.s))})", k)
349
+
350
+ def decimal_to_int(self, a: str) -> str:
351
+ # Truncates toward zero; ANSI raises outside 64 bits.
352
+ return f"CAST({a} AS BIGINT)"
353
+
354
+ def decimal_div(self, a: str, b: str, sa: int, k: Dec) -> str:
355
+ raise self.to_duckdb(
356
+ "decimal division (an AVG of decimals) on Spark: Spark's decimal quotient "
357
+ "rounds at a scale of its own first (spark-decimal-arith)",
358
+ "see #27",
359
+ "cast it to DOUBLE",
360
+ )
361
+
362
+ def float_extreme(self, fn: str, v: str, over: str) -> str:
363
+ # NaN is the greatest double, and -0.0 equals 0.0, keeping whichever
364
+ # came first (spark-nan-order, spark-zero-order): the codes' order up
365
+ # to the zero, which `canon` makes the one zero (`Shim.one_zero`).
366
+ return self.canon(f"{fn}({v}) {over}" if over else f"{fn}({v})")
367
+
368
+ def like_pattern(self, p: str) -> str:
369
+ odd = f"({p} RLIKE {self.str_lit(r'(^|[^\\])(\\\\)*\\$')})"
370
+ return f"(CASE WHEN {odd} THEN concat({p}, {self.str_lit(chr(92))}) ELSE {p} END)"
371
+
372
+ def substring(self, s: str, start: str, length: str | None) -> str:
373
+ return (
374
+ f"substring({s}, {start})" if length is None else f"substring({s}, {start}, {length})"
375
+ )
376
+
377
+ def regex_search(self, s: str, pattern: str) -> str:
378
+ return f"({s} RLIKE {self.str_lit(pattern)})"
379
+
380
+ # Windows
381
+
382
+ def over(self, partition: Sequence[str], order: Sequence[str]) -> str:
383
+ if not order:
384
+ raise self.to_duckdb("Spark window functions need an ORDER BY")
385
+ return super().over(partition, order)
386
+
387
+ def lag(self, x: str, offset: int, default: str, over: str) -> str:
388
+ return x if offset == 0 else super().lag(x, offset, default, over)
389
+
390
+ def lead(self, x: str, offset: int, default: str, over: str) -> str:
391
+ return x if offset == 0 else super().lead(x, offset, default, over)
392
+
393
+ # Relations
394
+
395
+ def row_ordinal(self) -> str:
396
+ raise Unsupported(
397
+ "Spark tables have no row order, so FETCH and windows over a named table "
398
+ "cannot follow the Lean model's list order (windows run with deterministic=True)"
399
+ )
400
+
401
+
402
+ def _float_const(sql: str) -> float | None:
403
+ """The value of a `float_lit` constant, or None for other SQL."""
404
+ m = re.fullmatch(r"CAST\('([^']*)' AS DOUBLE\)", sql)
405
+ return float(m.group(1)) if m else None
406
+
407
+
408
+ SPARK: Dialect = SparkDialect("spark")
@@ -0,0 +1,194 @@
1
+ """Spark as an engine, through SQL generated from the plan (`pip install
2
+ 'sverify[spark]'`, and a JVM: Java 17 or 21 on `PATH` or in `JAVA_HOME`).
3
+
4
+ Internal: not part of sverify-spark's public API, which is `PLUGIN` and the
5
+ dialect (`sverify_spark.dialect`: `SPARK`, `SPARK_CONF`); it may change in any
6
+ release.
7
+
8
+ `run` writes the plan as Spark SQL with `sverify.sql.to_sql` (whose semantics
9
+ are Lean's `Rel.eval`, see `sverify_spark.dialect`) and runs it on a Spark
10
+ session holding the given tables as temporary views. `session()` is a local
11
+ session with the settings of `SPARK_CONF`; on a cluster or Databricks, pass
12
+ your own session, configured the same way. Plans that need a table's row
13
+ order are refused (`Unsupported`) unless `deterministic=True`.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import functools
19
+ import os
20
+ import re
21
+ import sys
22
+ import weakref
23
+ from collections.abc import Mapping
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ import pyarrow as pa
27
+
28
+ from sverify.sql import to_sql
29
+ from sverify_spark.dialect import SPARK, SPARK_CONF
30
+
31
+ try:
32
+ import pyspark # noqa: F401
33
+ except ImportError as e:
34
+ raise ImportError("the Spark engine needs pyspark: pip install 'sverify[spark]'") from e
35
+
36
+ if TYPE_CHECKING:
37
+ from pyspark.sql import SparkSession
38
+
39
+
40
+ #: Settings of the local session beyond `SPARK_CONF`. The parser's ANTLR DFA
41
+ #: cache is static and unbounded unless Spark manages it: the nested SQL that
42
+ #: `to_sql` writes for date arithmetic (one 51 kB query of
43
+ #: `tests/test_backends.py`) left about 740 MB of a 1 GB driver heap in it,
44
+ #: and later queries failed with `AGGREGATE_OUT_OF_MEMORY` or could not
45
+ #: broadcast. Flushing it at 10 % of the heap keeps it near 100 MB.
46
+ LOCAL_CONF: dict[str, str] = {
47
+ "spark.ui.enabled": "false",
48
+ "spark.sql.shuffle.partitions": "2",
49
+ "spark.log.level": "OFF",
50
+ "spark.sql.parser.manageParserCaches": "true",
51
+ "spark.sql.parser.parserDfaCacheFlushRatio": "10",
52
+ }
53
+
54
+
55
+ def driver_memory(limit: str) -> str:
56
+ """`SVERIFY_MEMORY_LIMIT` (#783) as Spark's `spark.driver.memory`:
57
+ `"2GB"` is `"2g"`, `"512MB"` is `"512m"`."""
58
+ m = re.fullmatch(r"\s*(\d+)\s*([KMGT])i?B?\s*", limit, re.IGNORECASE)
59
+ if m is None:
60
+ raise ValueError(f"memory limit {limit!r}: write a size such as 2GB or 512MB")
61
+ return f"{m[1]}{m[2].lower()}"
62
+
63
+
64
+ @functools.cache
65
+ def session() -> SparkSession:
66
+ """A local Spark session (one per process) with the settings of
67
+ `SPARK_CONF` and `LOCAL_CONF`. `SVERIFY_MEMORY_LIMIT` sets the driver's
68
+ memory (Spark's default is 1 GB) when the session's JVM starts. Python
69
+ workers run this process's interpreter unless `PYSPARK_PYTHON` names
70
+ another."""
71
+ from pyspark.sql import SparkSession
72
+
73
+ builder = SparkSession.builder.master("local[2]").appName("sverify")
74
+ conf = SPARK_CONF | LOCAL_CONF
75
+ if limit := os.environ.get("SVERIFY_MEMORY_LIMIT", "").strip():
76
+ conf["spark.driver.memory"] = driver_memory(limit)
77
+ for k, v in conf.items():
78
+ builder = builder.config(k, v)
79
+ spark = builder.getOrCreate()
80
+ spark.sparkContext.setLogLevel("OFF")
81
+ if not os.environ.get("PYSPARK_PYTHON"):
82
+ # Python workers run this interpreter, not whichever `python3` is
83
+ # first on `PATH` (a virtual environment need not be on it).
84
+ spark.sparkContext.pythonExec = sys.executable
85
+ return spark
86
+
87
+
88
+ def spark_type(t: pa.DataType) -> str:
89
+ """The Spark type of an Arrow column, as `sverify_spark.dialect` writes it."""
90
+ if pa.types.is_integer(t):
91
+ return SPARK.type_name("int")
92
+ if pa.types.is_decimal(t):
93
+ return f"DECIMAL({t.precision}, {t.scale})"
94
+ if pa.types.is_floating(t):
95
+ return SPARK.type_name("float")
96
+ if pa.types.is_timestamp(t):
97
+ if t.tz is not None:
98
+ raise TypeError(f"{t}: only timestamps without a time zone (TIMESTAMP_NTZ)")
99
+ return SPARK.type_name("time")
100
+ if pa.types.is_date(t):
101
+ return SPARK.type_name("date")
102
+ if pa.types.is_boolean(t):
103
+ return SPARK.type_name("bool")
104
+ if pa.types.is_string(t) or pa.types.is_large_string(t):
105
+ return SPARK.type_name("str")
106
+ if pa.types.is_list(t) or pa.types.is_large_list(t):
107
+ return f"ARRAY<{spark_type(t.value_type)}>"
108
+ raise TypeError(f"no Spark type for {t}")
109
+
110
+
111
+ def arrow_type(t: pa.DataType) -> pa.DataType:
112
+ """The Arrow type Spark reads as `spark_type(t)`: 64-bit integers and
113
+ doubles, microsecond timestamps, plain strings and lists."""
114
+ if pa.types.is_integer(t):
115
+ return pa.int64()
116
+ if pa.types.is_floating(t):
117
+ return pa.float64()
118
+ if pa.types.is_timestamp(t):
119
+ return pa.timestamp("us")
120
+ if pa.types.is_string(t) or pa.types.is_large_string(t):
121
+ return pa.string()
122
+ if pa.types.is_list(t) or pa.types.is_large_list(t):
123
+ return pa.list_(arrow_type(t.value_type))
124
+ return t
125
+
126
+
127
+ #: The views sverify registered under its own names (`__sverify_<i>`, which
128
+ #: `sverify.engine.run_plan` gives a plan's tables), per session: the Arrow
129
+ #: table each holds. A run over the same table does not send it again.
130
+ _VIEWS: weakref.WeakKeyDictionary[Any, dict[str, pa.Table]] = weakref.WeakKeyDictionary()
131
+
132
+
133
+ def put_tables(tables: Mapping[str, pa.Table], spark: SparkSession | None = None) -> None:
134
+ """Register each table as a temporary view of that name. The columns go
135
+ to Spark as Arrow, cast to the types `spark_type` names, so NULL and NaN
136
+ stay apart, and no Python worker runs (a table of 100,000 rows takes a
137
+ quarter of the time it took as Python values). A view of sverify's own
138
+ names that holds the same Arrow table already is kept as it is."""
139
+ spark = spark or session()
140
+ held = _VIEWS.setdefault(spark, {})
141
+ for name, table in tables.items():
142
+ own = name.startswith("__sverify_")
143
+ if own and held.get(name) is table:
144
+ continue
145
+ schema = ", ".join(f"{SPARK.quote(f.name)} {spark_type(f.type)}" for f in table.schema)
146
+ target = pa.schema([pa.field(f.name, arrow_type(f.type)) for f in table.schema])
147
+ spark.createDataFrame(table.cast(target), schema).createOrReplaceTempView(name)
148
+ if own:
149
+ held[name] = table
150
+
151
+
152
+ def run(
153
+ plan: str | dict,
154
+ tables: Mapping[str, pa.Table],
155
+ spark: SparkSession | None = None,
156
+ *,
157
+ deterministic: bool = False,
158
+ finite: bool = True,
159
+ ) -> pa.Table:
160
+ """Run a Substrait JSON plan on Spark over `tables` (temporary views).
161
+
162
+ The plan is written as Spark SQL by `sverify.engines.to_sql` in the
163
+ `sverify_spark.dialect.SPARK` dialect. `sverify.engines.run(con, plan,
164
+ "spark")` runs a plan over a connection's tables the same way.
165
+
166
+ Args:
167
+ plan: A Substrait JSON plan, as a string or parsed.
168
+ tables: The tables the plan reads, by name. Each is registered as a
169
+ temporary view of that name, replacing any view of the same name.
170
+ spark: The Spark session to run on, configured with
171
+ `sverify_spark.dialect.SPARK_CONF`. Default: a local session with
172
+ those settings.
173
+ deterministic: Promise that no two rows tie on any window's
174
+ `PARTITION BY` and `ORDER BY` columns (what a contract report's
175
+ `deterministic` says), so windows run without a row-order
176
+ tiebreak (see `sverify.engines.to_sql`). Default False.
177
+ finite: Check that no operation on finite doubles gives `±∞`, the
178
+ reference's precondition (#575); False for a plan verified
179
+ under a profile that allows `±∞`, as Spark's does. Default True.
180
+
181
+ Returns:
182
+ The plan's result, as an Arrow table.
183
+
184
+ Raises:
185
+ sverify.engines.UnsupportedError: Spark SQL cannot express the plan with
186
+ Lean's meaning, for example a plan that needs a table's row order
187
+ without `deterministic=True`.
188
+ TypeError: A column has a type Spark cannot hold here, such as a
189
+ timestamp with a time zone.
190
+ """
191
+ spark = spark or session()
192
+ sql = to_sql(plan, SPARK, deterministic=deterministic, finite=finite)
193
+ put_tables(tables, spark)
194
+ return spark.sql(sql).toArrow()
sverify_spark/store.py ADDED
@@ -0,0 +1,12 @@
1
+ """Spark's store, for now (#1189, interim): its views' state as Arrow
2
+ tables in the Python process, with the operations of `sverify._arrow_state`,
3
+ until the cluster holds it keeps it natively (`SparkStore`).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from sverify._arrow_state import ArrowOps
9
+
10
+
11
+ class ArrowStore(ArrowOps):
12
+ """Spark's views' state as Arrow tables in the Python process."""
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.5
2
+ Name: sverify-spark
3
+ Version: 0.8.0
4
+ Summary: Spark as an engine of sverify: plans verified in Lean, written as Spark SQL
5
+ Project-URL: Source, https://github.com/AlexanderNenninger/substrait-lean/tree/main/engines/spark
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: pyspark>=4.0; extra == 'run'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # sverify-spark
16
+
17
+ Sverify-spark 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
+ Spark as an engine of [sverify](https://github.com/AlexanderNenninger/substrait-lean):
22
+ a plan verified in Lean is written as Spark SQL, with a shim where Spark
23
+ differs from the reference, and runs on a Spark session under ANSI mode.
24
+ `pip install sverify[spark]` installs it with PySpark; `sverify-spark` alone
25
+ writes Spark SQL (`sverify_spark.dialect.SPARK`) without PySpark. sverify finds
26
+ it through its `ProfilePlugin` in the entry-point group `sverify.profiles`.
27
+
28
+ The directory holds the whole engine package:
29
+
30
+ - `src/sverify_spark/`: the plugin (`PLUGIN`), the dialect (`dialect`:
31
+ `SPARK`, `SPARK_CONF`) and the runner on a Spark session (`engine`);
32
+ - `facts/`: what Spark does at each of the core's options, the evidence for
33
+ `Profile.spark` ([facts/README.md](facts/README.md));
34
+ - `probes/`: the probes' and the fuzzer's recordings the facts cite;
35
+ - `tests/`: its tests, which run in sverify's test session
36
+ (`python/pyproject.toml`'s `testpaths`).
37
+
38
+ Its Lean half, the profile and its shims, is in the root Lean package for now
39
+ (`SubstraitLean/SparkProfile.lean`, `SparkShims.lean`).
@@ -0,0 +1,9 @@
1
+ sverify_spark/__init__.py,sha256=xx4yRu0cF1XE5EASNwnfWL5daVM1dW784KkZ3iNiKec,6435
2
+ sverify_spark/dialect.py,sha256=L2dgLaVpzl3HKFm772Ujkf_51bAha77sWaNCvSy9K3Y,18345
3
+ sverify_spark/engine.py,sha256=18MsfMbcT3Uz3lMxli03_iswy-X7GFmGprR3NLeTowk,8119
4
+ sverify_spark/store.py,sha256=RD-w7zyFl_pvLPPPMDs9bxWIGMqEYcQqSQN0eOepO00,391
5
+ sverify_spark-0.8.0.dist-info/METADATA,sha256=ZuObsEA3mWjBpZz9tcofDp5LECYN1m9P_dPuQOpIJnc,1803
6
+ sverify_spark-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ sverify_spark-0.8.0.dist-info/entry_points.txt,sha256=SNWfL6iSa5w1rHwnco_4NuvRoR4f_ZH3UH6GwTzNbv8,48
8
+ sverify_spark-0.8.0.dist-info/licenses/LICENSE,sha256=Pz2eACSxkhsGfW9_iN60pgy-enjnbGTj8df8O3ebnQQ,16726
9
+ sverify_spark-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
+ spark = sverify_spark: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.