diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 652a610..7ffefc1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ jobs: uses: actions/checkout@v7 with: &specification-checkout repository: OpenStatSpec/specification - ref: 864e84479f554b8ee250ffed44c4dfb963750d4a + ref: d76121ec343cf9614fb8ad2f8cc50f72ee29966e path: openstatspec-specification - name: Checkout required SPSS engine uses: actions/checkout@v7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 33f212d..6046fe4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,7 +48,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: OpenStatSpec/specification - ref: 864e84479f554b8ee250ffed44c4dfb963750d4a + ref: d76121ec343cf9614fb8ad2f8cc50f72ee29966e path: openstatspec-specification - name: Checkout specification package source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0593c9b..700a813 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,59 @@ All notable changes to this reference implementation are documented here. +## 0.10.0 - 2026-12-01 + +This minor release aligns the adapter with Conformance Supplement 0.6 of +specification `v0.6.0`. Several diagnostics change for existing callers, and +imports that contain negative zero are now refused instead of silently +storing positive zero. + +### Changed + +- `compile_spss_request` and the `frontend_contract` selector report + `request_schema_invalid` instead of `invalid_spss_request`. Duplicate + variable names (case-insensitive) and a numeric value label on a string + variable report the same code. +- A string compared with a number reports `expression_type_unsupported` + instead of `type_mismatch`, in both frontends and for raw plans in binding. +- Arithmetic in a `COMPUTE` value or inside an `IF` predicate, including `*` + and `**`, reports `expression_type_unsupported`. `*` is now a token, so + `SELECT * FROM q1.` reports `unsupported_spss_command`. +- A `replace` recode whose target is not its source reports + `target_already_exists` instead of `invalid_transformation_plan`. +- `RECODE q1 (ELSE = 0).` and text after the last terminated command without + a period report `spss_syntax_error`. +- `AND OR NOT TO EQ NE LT LE GT GE BY ALL WITH` are never variable names or + targets (`spss_syntax_error`). `NaN` and `Infinity` may now name variables + and are refused only in operand position. +- Official Frontend 0.3 `*` and `COMMENT` comments end at a period followed + by whitespace or the end of the input, so `* ratio 1.5 is kept.` is one + comment. +- The default frontend (Frontend 0.2) refuses slash-separated `FORMATS` + groups with `spss_syntax_error`. Keywords match ASCII case-insensitively + only, on both frontends. +- Variable names match by the unconditional per-code-point lowercase mapping + instead of Unicode case folding, in the frontends, plan binding and + in-place apply. `STRASSE` no longer matches `straße`; `ÄRA` still matches + `ära`. +- SAV/ZSAV import refuses negative zero before mutation with + `target_capability_exceeded` (reason `negative_zero_numeric_value`) on every + SQL profile. Capabilities declare `negative_zero: reject_before_mutation`; + the NaN reader policy is unchanged. + +### Added + +- `tests/test_conformance_supplement.py` runs the seven supplement manifests + of the pinned specification checkout: Frontend 0.1, 0.2 and 0.3, Plan 0.1 + and 0.2, In-Place 0.1 on SQLite, and SAV/ZSAV 1.0 on SQLite with the + runner-generated negative-zero and NaN fixtures. + +The specification is pinned to released `v0.6.0` at exact commit +`d76121ec343cf9614fb8ad2f8cc50f72ee29966e`; the required SPSS codec remains +`openstatspec-pyspssio==0.5.1.post2`. Python claims no Frontend 0.1 contract, +so the supplement case that refuses Frontend 0.2 commands under the 0.1 +contract is skipped. + ## 0.9.1 - 2026-11-09 This patch release speeds up SAV import and export. Behavior, error codes and diff --git a/README.md b/README.md index fbe9bf4..97616b2 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ The reference Python implementation of the OpenStatSpec specification. This package implements the specification; it does not define or extend it. The normative model lives in the `OpenStatSpec/specification` repository. -Python 0.9.1 pins released specification `v0.5.0` at -`864e84479f554b8ee250ffed44c4dfb963750d4a` and selects SAV/ZSAV 1.0 with +Python 0.10.0 pins released specification `v0.6.0` at +`d76121ec343cf9614fb8ad2f8cc50f72ee29966e` and selects SAV/ZSAV 1.0 with `database_io_policy=openstatspec-database-io-v1`. It implements the explicitly selected optional official SPSS Frontend 0.3 over unchanged Plan 0.1/0.2, not the separate optional Transformation Workflow 0.3 profile. @@ -25,6 +25,12 @@ Unsupported source features, SQL targets, or export paths fail explicitly. There is no silent truncation, type conversion, metadata loss, or partial import. +Numeric source values must be finite binary64 or system missing. A SAV NaN +becomes SQL NULL (system missing) under the declared +`canonicalize_to_sql_null_during_spss_decode` reader policy. Infinities and +negative zero are refused before mutation on every SQL profile, because not +every profile keeps the sign of zero. + ## Package layout - `openstatspec.core`: pure standard concepts, validation, versions, diff --git a/docs/release-readiness.md b/docs/release-readiness.md index 4288c07..9801325 100644 --- a/docs/release-readiness.md +++ b/docs/release-readiness.md @@ -86,8 +86,9 @@ The canonical transformation core and SPSS syntax frontend are separate public surfaces. A release must run the specification-owned canonical-plan and SPSS frontend conformance fixtures, including `tests/test_frontend_v03.py` with all 90 effective official Frontend 0.3 cases (35 declared plus inherited cases with -published overrides/supersessions) from exact specification commit -`864e84479f554b8ee250ffed44c4dfb963750d4a`. Then exercise the generic plan apply +published overrides/supersessions) and `tests/test_conformance_supplement.py` +with the seven Conformance Supplement 0.6 manifests from exact specification +commit `d76121ec343cf9614fb8ad2f8cc50f72ee29966e`. Then exercise the generic plan apply API, SPSS compatibility apply path, and explicitly selected official 0.3 apply. Python schema-extension and legacy acceptance tests are separate compatibility evidence, not official Plan 0.3 conformance; no official Plan 0.3 exists. @@ -260,9 +261,9 @@ publication evidence. No push, PR, tag or publication was performed. without a database connection. 5. Confirm `openstatspec capabilities` reflects the intended support boundary. 6. Confirm CI, release fixtures, and capabilities use the published OpenStatSpec - specification `v0.5.0` at exact commit - `864e84479f554b8ee250ffed44c4dfb963750d4a`, publish - `specification_status=released`, and set `specification_release` to `v0.5.0`. + specification `v0.6.0` at exact commit + `d76121ec343cf9614fb8ad2f8cc50f72ee29966e`, publish + `specification_status=released`, and set `specification_release` to `v0.6.0`. Use an exact checkout via `OPENSTATSPEC_SPECIFICATION_DIR` for local tests. 7. Review this document, the README, and CHANGELOG for accurate scope. Finalize the 0.9.0 changelog date as 2026-09-10 before selecting the final release commit. diff --git a/docs/transformations.md b/docs/transformations.md index fe22288..553bdb9 100644 --- a/docs/transformations.md +++ b/docs/transformations.md @@ -71,7 +71,7 @@ boundary. It accepts **only** `openstatspec-spss-syntax-frontend-v0.3`, with exact required fields `contract`, `input_alias`, `input_schema`, and `source_text`. Unknown fields, missing fields, wrong types, noncanonical or nonfinite typed codes, ambiguous variable names, and mismatched label types -fail closed. Request-shape failures report `invalid_spss_request`; source +fail closed. Request-shape failures report `request_schema_invalid`; source failures retain the normative diagnostics. It returns no partial compilation. ```python @@ -104,6 +104,19 @@ Comments remain in the LF-normalized source hash but emit no operation; comment-only input is invalid. Python `STRING` and `DELETE VARIABLES` are rejected under the official selector. +Conformance Supplement 0.6 rules apply to the official request and to the +default frontend: a `*` or `COMMENT` comment ends at a period followed by +whitespace or the end of the input; every command, including the last, needs +its terminating period; `AND OR NOT TO EQ NE LT LE GT GE BY ALL WITH` are +never variable names or targets; `NaN` and `Infinity` may name variables but +are refused as operands; `ELSE`-only `RECODE` is a syntax error; arithmetic +(including `*`) in a `COMPUTE` value or an `IF` predicate and any string to +number comparison report `expression_type_unsupported`. The default frontend +refuses slash-separated `FORMATS` groups, as Frontend 0.2 requires. Variable +names match by the unconditional per-code-point lowercase mapping, not case +folding, so `STRASSE` does not match `straße`. A plan `replace` recode whose +target is not its source reports `target_already_exists`. + **Explicit implementation decision:** precedence is standard SPSS order, comparisons → `NOT` → `AND` → `OR` (tightest first). Thus `NOT a = 1 AND b = 1` means `(NOT (a = 1)) AND b = 1`, not negation of the conjunction. @@ -127,9 +140,11 @@ the existing CLI remains on that compatibility path. Evidence: `tests/test_frontend_v03.py` runs the 35 declared and all 90 effective cases from specification commit -`864e84479f554b8ee250ffed44c4dfb963750d4a`, applying only the published inherited +`d76121ec343cf9614fb8ad2f8cc50f72ee29966e` (`v0.6.0`), applying only the published inherited contract overrides and two comment supersessions. It checks exact Plan 0.1/0.2 objects/hashes, source hashes, diagnostics, and declared output metadata. +`tests/test_conformance_supplement.py` runs the Conformance Supplement 0.6 +manifests of the same checkout. Local SQLite integration checks UNKNOWN, sequential data and metadata, identity, audit provenance, and absence of copy/history artifacts. Existing frontend, plan, and in-place suites remain in the gate. This is not new service diff --git a/pyproject.toml b/pyproject.toml index 8aa8d8f..1e37886 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openstatspec" -version = "0.9.1" +version = "0.10.0" description = "Reference adapter for the OpenStatSpec relational contract" readme = "README.md" requires-python = ">=3.11" diff --git a/src/openstatspec/frontends/spss/binding.py b/src/openstatspec/frontends/spss/binding.py index 1183f7b..4ecec6e 100644 --- a/src/openstatspec/frontends/spss/binding.py +++ b/src/openstatspec/frontends/spss/binding.py @@ -18,7 +18,7 @@ TransformationPlan, TypedValue, ValueLabel, ) from ...transform.schema import ( - BoundTransformation, StorageKind, VariableDefinition, VariableSchema, + BoundTransformation, StorageKind, VariableDefinition, VariableSchema, name_key, ) from ...transform.validation import bind_transformation_plan from .syntax import ( @@ -48,7 +48,7 @@ def _resolve( ) -> tuple[int, VariableDefinition]: matches = [ (index, variable) for index, variable in enumerate(variables) - if variable.name.casefold() == name.casefold() + if name_key(variable.name) == name_key(name) ] if len(matches) != 1: raise frontend_error( @@ -86,18 +86,12 @@ def _bind_predicate( return _bind_predicate(expanded, variables, negated=negated and syntax.operator == "ne") left, left_type = _bind_operand(syntax.left, variables) right, right_type = _bind_operand(syntax.right, variables) - if left_type != right_type: + if "string" in (left_type, right_type): raise frontend_error( - "type_mismatch", - "Comparison operands must have the same storage kind.", + "expression_type_unsupported", + "String comparisons are outside the bounded frontend.", span=syntax.span, left_type=left_type, right_type=right_type, ) - if syntax.operator != "=" and left_type != "binary64": - raise frontend_error( - "type_mismatch", - "Ordered comparisons require numeric operands.", - span=syntax.span, operator=syntax.operator, - ) operator = ({"=": "=", "<": ">=", "<=": ">", ">": "<=", ">=": "<"}[syntax.operator] if negated else syntax.operator) return ComparisonExpression(left, operator, right) assert isinstance(syntax, BooleanSyntax) @@ -129,7 +123,7 @@ def _assignment( ) matches = [ (index, variable) for index, variable in enumerate(variables) - if variable.name.casefold() == target_name.casefold() + if name_key(variable.name) == name_key(target_name) ] if matches: _, target = matches[0] @@ -286,7 +280,7 @@ def _bind_recode( span=target_span, target=target_name, ) if any( - variable.name.casefold() == target_name.casefold() + name_key(variable.name) == name_key(target_name) for variable in variables ): raise frontend_error( @@ -404,7 +398,7 @@ def bind_spss_syntax( target=variable_token.text, ) if any( - variable.name.casefold() == variable_token.text.casefold() + name_key(variable.name) == name_key(variable_token.text) for variable in variables ): raise frontend_error( @@ -446,7 +440,7 @@ def bind_spss_syntax( condition = _bind_predicate(command.condition, variables) target_matches = [ (index, variable) for index, variable in enumerate(variables) - if variable.name.casefold() == command.target.text.casefold() + if name_key(variable.name) == name_key(command.target.text) ] if len(target_matches) != 1: raise frontend_error( diff --git a/src/openstatspec/frontends/spss/compiler.py b/src/openstatspec/frontends/spss/compiler.py index 6897089..1db3a5f 100644 --- a/src/openstatspec/frontends/spss/compiler.py +++ b/src/openstatspec/frontends/spss/compiler.py @@ -61,7 +61,7 @@ def compile_spss_syntax( ) -> SpssFrontendCompilation: """Parse and bind source without SQL generation or database mutation.""" if frontend_contract not in (None, SPSS_FRONTEND_V03_CONTRACT): - raise frontend_error("invalid_spss_request", "Select the exact official Frontend 0.3 contract or omit the selector for legacy behavior.") + raise frontend_error("request_schema_invalid", "Select the exact official Frontend 0.3 contract or omit the selector for legacy behavior.") normalized = normalize_spss_source(source) program = parse_spss_syntax(normalized, official_v03=frontend_contract is not None) try: @@ -81,7 +81,7 @@ def compile_spss_syntax( def compile_spss_request(request: Mapping[str, Any]) -> SpssFrontendCompilation: """Validate the exact official Frontend 0.3 request, then use the shared frontend.""" def invalid(): - raise frontend_error("invalid_spss_request", "Request must conform to the official Frontend 0.3 schema.") + raise frontend_error("request_schema_invalid", "Request must conform to the official Frontend 0.3 schema.") if not isinstance(request, Mapping) or set(request) != {"contract", "input_alias", "input_schema", "source_text"}: invalid() @@ -133,5 +133,5 @@ def invalid(): )) schema = VariableSchema(tuple(variables)) except (ValueError, TypeError, OverflowError) as error: - raise frontend_error("invalid_spss_request", "Invalid Frontend 0.3 input schema.") from error + raise frontend_error("request_schema_invalid", "Invalid Frontend 0.3 input schema.") from error return compile_spss_syntax(request["source_text"], schema, input_alias=request["input_alias"], frontend_contract=SPSS_FRONTEND_V03_CONTRACT) diff --git a/src/openstatspec/frontends/spss/syntax.py b/src/openstatspec/frontends/spss/syntax.py index febb499..5f9a333 100644 --- a/src/openstatspec/frontends/spss/syntax.py +++ b/src/openstatspec/frontends/spss/syntax.py @@ -14,7 +14,7 @@ TokenKind = Literal[ "identifier", "number", "string", "left_paren", "right_paren", "equals", "less", "less_equal", "greater", "greater_equal", - "comma", "plus", "minus", "slash", "period", "eof", "not_equal", + "comma", "plus", "minus", "slash", "period", "eof", "not_equal", "star", ] @@ -219,6 +219,16 @@ class SpssSyntaxProgram: ) _IDENTIFIER_START = frozenset("_@$#") _IDENTIFIER_CONTINUE = frozenset("_@$#") +# A comment ends at a period followed by whitespace or the end of the input. +_COMMENT_END = re.compile(r"\.(?=\s|\Z)") +RESERVED_WORDS = frozenset({ + "and", "or", "not", "to", "eq", "ne", "lt", "le", "gt", "ge", "by", "all", "with", +}) + + +def _ascii_keyword(text: str) -> str | None: + """Keywords match ASCII case-insensitively only.""" + return text.lower() if text.isascii() else None def _position(source: str, offset: int) -> SourcePosition: @@ -259,7 +269,7 @@ def tokenize_spss(source: str, *, official_v03: bool = False) -> tuple[Token, .. punctuation: dict[str, TokenKind] = { "(": "left_paren", ")": "right_paren", "=": "equals", "<": "less", ">": "greater", ",": "comma", "+": "plus", - "-": "minus", "/": "slash", ".": "period", + "-": "minus", "/": "slash", ".": "period", "*": "star", } while offset < len(source): character = source[offset] @@ -275,10 +285,10 @@ def tokenize_spss(source: str, *, official_v03: bool = False) -> tuple[Token, .. continue boundary = not tokens or tokens[-1].kind == "period" if official_v03 and boundary and character == "*": - end = source.find(".", offset) - if end < 0: + end = _COMMENT_END.search(source, offset) + if end is None: raise frontend_error("spss_syntax_error", "Expected '.' after comment.", span=_span(source, offset, len(source))) - offset = end + 1 + offset = end.end() continue if character in {"'", '"'}: start = offset @@ -345,18 +355,12 @@ def tokenize_spss(source: str, *, official_v03: bool = False) -> tuple[Token, .. continue break text = source[start:offset] - if official_v03 and boundary and text.isascii() and text.casefold() == "comment": - end = source.find(".", offset) - if end < 0: + if official_v03 and boundary and _ascii_keyword(text) == "comment": + end = _COMMENT_END.search(source, offset) + if end is None: raise frontend_error("spss_syntax_error", "Expected '.' after comment.", span=_span(source, start, len(source))) - offset = end + 1 + offset = end.end() continue - if text.casefold() in {"nan", "infinity"}: - raise frontend_error( - "spss_syntax_error", - "NaN and Infinity are not finite-number tokens.", - span=_span(source, start, offset), - ) tokens.append(Token( "identifier", text, text, _span(source, start, offset), )) @@ -414,11 +418,31 @@ def accepts(self, kind: TokenKind) -> Token | None: def accepts_keyword(self, keyword: str) -> Token | None: token = self.current - if (token.kind == "identifier" and token.text.casefold() == keyword.casefold() - and (not self.official_v03 or token.text.isascii())): + if token.kind == "identifier" and _ascii_keyword(token.text) == keyword.lower(): return self.advance() return None + def name(self, detail: str) -> Token: + """Expect a variable name; reserved words are never names.""" + token = self.expects("identifier", detail) + self.reject_reserved((token,)) + return token + + @staticmethod + def reject_reserved(tokens: tuple[Token | VariableRangeSyntax, ...]) -> None: + for token in tokens: + endpoints = ( + (token.first, token.last, *token.continuations) + if isinstance(token, VariableRangeSyntax) else (token,) + ) + for endpoint in endpoints: + if _ascii_keyword(endpoint.text) in RESERVED_WORDS: + raise frontend_error( + "spss_syntax_error", + f"Reserved word {endpoint.text!r} cannot be a variable name.", + span=endpoint.span, + ) + def expects(self, kind: TokenKind, detail: str) -> Token: token = self.accepts(kind) if token is None: @@ -434,7 +458,9 @@ def expects_keyword(self, keyword: str) -> Token: ) return token - def variable_list(self, *, stop_kinds: frozenset[str]) -> tuple[Token | VariableRangeSyntax, ...]: + def variable_list( + self, *, stop_kinds: frozenset[str], reserved: bool = True, + ) -> tuple[Token | VariableRangeSyntax, ...]: variables: list[Token | VariableRangeSyntax] = [] while self.current.kind not in stop_kinds: if not self.official_v03 and self.accepts("comma") is not None: @@ -454,6 +480,8 @@ def variable_list(self, *, stop_kinds: frozenset[str]) -> tuple[Token | Variable "spss_syntax_error", "Expected at least one variable name.", span=self.current.span, ) + if reserved: + self.reject_reserved(tuple(variables)) return tuple(variables) def literal(self) -> SyntaxLiteral: @@ -473,10 +501,27 @@ def literal(self) -> SyntaxLiteral: def operand(self) -> OperandSyntax: if self.current.kind == "identifier": - token = self.advance() - return OperandSyntax("variable", token.span, variable=token) - literal = self.literal() - return OperandSyntax("literal", literal.span, literal=literal) + if _ascii_keyword(self.current.text) in {"nan", "infinity"}: + raise frontend_error( + "spss_syntax_error", + "NaN and Infinity are not finite-number tokens.", + span=self.current.span, + ) + token = self.name("Expected a variable name.") + operand = OperandSyntax("variable", token.span, variable=token) + else: + literal = self.literal() + operand = OperandSyntax("literal", literal.span, literal=literal) + if ( + self.current.kind in {"plus", "minus", "slash", "star"} + or (self.current.kind == "number" and self.current.text.startswith("-")) + ): + raise frontend_error( + "expression_type_unsupported", + "Arithmetic expressions are outside the bounded frontend.", + span=self.current.span, + ) + return operand def comparison(self) -> PredicateSyntax: if self.accepts("left_paren") is not None: @@ -491,7 +536,7 @@ def comparison(self) -> PredicateSyntax: token = self.current if self.official_v03: operators["not_equal"] = "ne" - if token.kind == "identifier" and token.text.isascii() and token.text.casefold() == "ne": + if token.kind == "identifier" and _ascii_keyword(token.text) == "ne": operators["identifier"] = "ne" if token.kind not in operators: raise frontend_error( @@ -531,21 +576,9 @@ def predicate(self) -> PredicateSyntax: ) def compute(self, start: Token) -> ComputeCommandSyntax: - target = self.expects("identifier", "COMPUTE requires a target variable.") + target = self.name("COMPUTE requires a target variable.") self.expects("equals", "Expected '=' in COMPUTE.") value = self.operand() - if ( - self.current.kind in {"plus", "minus", "slash"} - or ( - self.current.kind == "number" - and self.current.text.startswith("-") - ) - ): - raise frontend_error( - "expression_type_unsupported", - "Arithmetic expressions are outside the bounded frontend.", - span=self.current.span, - ) end = self.expects("period", "Expected '.' after COMPUTE.") return ComputeCommandSyntax(target, value, _joined_span(start.span, end.span)) @@ -553,7 +586,7 @@ def if_command(self, start: Token) -> IfCommandSyntax: self.expects("left_paren", "Expected '(' before the IF predicate.") condition = self.predicate() self.expects("right_paren", "Expected ')' after the IF predicate.") - target = self.expects("identifier", "IF requires a target variable.") + target = self.name("IF requires a target variable.") self.expects("equals", "Expected '=' in IF assignment.") value = self.operand() end = self.expects("period", "Expected '.' after IF.") @@ -562,12 +595,13 @@ def if_command(self, start: Token) -> IfCommandSyntax: def formats(self, start: Token) -> FormatsCommandSyntax: assignments: list[FormatAssignmentSyntax] = [] while self.current.kind not in {"period", "eof"}: - if assignments or not self.official_v03: + # Frontend 0.2 has no slash-separated FORMATS groups. + if assignments and self.official_v03: self.accepts("slash") variables = ( self.variable_list(stop_kinds=frozenset({"left_paren", "period", "eof", "slash"})) if self.official_v03 else - (self.expects("identifier", "FORMATS requires a variable name."),) + (self.name("FORMATS requires a variable name."),) ) self.expects("left_paren", "Expected '(' before an SPSS format.") format_token = self.expects("identifier", "Expected an SPSS format such as F1.0.") @@ -597,8 +631,8 @@ def variable_level(self, start: Token) -> VariableLevelCommandSyntax: ) self.expects("left_paren", "Expected '(' before a measurement level.") level = self.expects("identifier", "Expected NOMINAL, ORDINAL, or SCALE.") - normalized = level.text.casefold() - if normalized not in {"nominal", "ordinal", "scale"} or (self.official_v03 and not level.text.isascii()): + normalized = _ascii_keyword(level.text) + if normalized not in {"nominal", "ordinal", "scale"}: raise frontend_error( "spss_syntax_error", "Expected NOMINAL, ORDINAL, or SCALE.", @@ -634,7 +668,7 @@ def execute(self, start: Token) -> ExecuteCommandSyntax: @staticmethod def reject_to_range(variables: tuple[Token, ...], command: str) -> None: range_token = next( - (variable for variable in variables if variable.text.casefold() == "to"), + (variable for variable in variables if _ascii_keyword(variable.text) == "to"), None, ) if range_token is not None: @@ -646,9 +680,10 @@ def reject_to_range(variables: tuple[Token, ...], command: str) -> None: def string(self, start: Token) -> StringCommandSyntax: variables = self.variable_list( - stop_kinds=frozenset({"left_paren", "period", "eof"}), + stop_kinds=frozenset({"left_paren", "period", "eof"}), reserved=False, ) self.reject_to_range(variables, "STRING") + self.reject_reserved(variables) self.expects("left_paren", "Expected '(' before a STRING width.") width_token = self.expects( "identifier", "STRING requires a width such as A20.", @@ -676,8 +711,9 @@ def string(self, start: Token) -> StringCommandSyntax: def delete_variables(self, start: Token) -> DeleteVariablesCommandSyntax: self.expects_keyword("VARIABLES") - variables = self.variable_list(stop_kinds=frozenset({"period", "eof"})) + variables = self.variable_list(stop_kinds=frozenset({"period", "eof"}), reserved=False) self.reject_to_range(variables, "DELETE VARIABLES") + self.reject_reserved(variables) end = self.expects("period", "Expected '.' after DELETE VARIABLES.") return DeleteVariablesCommandSyntax( variables, _joined_span(start.span, end.span), @@ -739,6 +775,11 @@ def recode(self, start: Token) -> RecodeCommandSyntax: "spss_syntax_error", "RECODE requires at least one rule.", span=self.current.span, ) + if all(clause.match.kind == "else" for clause in clauses): + raise frontend_error( + "spss_syntax_error", "RECODE requires a rule before ELSE.", + span=clauses[0].span, + ) else_indexes = [ index for index, clause in enumerate(clauses) if clause.match.kind == "else" @@ -757,7 +798,7 @@ def recode(self, start: Token) -> RecodeCommandSyntax: targets = None if self.accepts_keyword("INTO") is not None: targets = self.variable_list(stop_kinds=frozenset({"period", "eof", "slash"}) if self.official_v03 else frozenset({"period", "eof"})) - if self.official_v03 and any(isinstance(target, VariableRangeSyntax) or target.text.casefold() == "to" for target in targets): + if self.official_v03 and any(isinstance(target, VariableRangeSyntax) for target in targets): raise frontend_error("spss_syntax_error", "INTO targets cannot use TO.", span=targets[0].span) if not self.official_v03 and len(targets) != len(sources): raise frontend_error( @@ -779,7 +820,7 @@ def variable_labels(self, start: Token) -> VariableLabelsCommandSyntax: variables = ( self.variable_list(stop_kinds=frozenset({"string", "period", "eof", "slash"})) if self.official_v03 else - (self.expects("identifier", "Expected a variable name."),) + (self.name("Expected a variable name."),) ) label = self.expects("string", "Expected a quoted variable label.") assignments.extend(VariableLabelSyntax( @@ -830,9 +871,18 @@ def value_labels(self, start: Token, *, additive: bool = False) -> ValueLabelsCo def parse(self) -> SpssSyntaxProgram: commands: list[SyntaxCommand] = [] + last_period = max( + (index for index, token in enumerate(self.tokens) if token.kind == "period"), + default=-1, + ) while self.current.kind != "eof": + if self.index > last_period: + raise frontend_error( + "spss_syntax_error", "Every command ends with a period.", + span=self.current.span, + ) start = self.expects("identifier", "Expected an SPSS command.") - command = start.text.casefold() if not self.official_v03 or start.text.isascii() else start.text + command = _ascii_keyword(start.text) if self.official_v03 and command in {"string", "delete"}: raise frontend_error("unsupported_spss_command", "Python schema commands are outside official Frontend 0.3.", span=start.span, command=start.text) if command == "recode": @@ -854,7 +904,7 @@ def parse(self) -> SpssSyntaxProgram: elif command == "delete": commands.append(self.delete_variables(start)) elif command == "variable": - if self.current.kind == "identifier" and self.current.text.casefold() == "level": + if self.current.kind == "identifier" and _ascii_keyword(self.current.text) == "level": commands.append(self.variable_level(start)) else: commands.append(self.variable_labels(start)) @@ -879,6 +929,13 @@ def parse(self) -> SpssSyntaxProgram: def parse_spss_syntax(source: str, *, official_v03: bool = False) -> SpssSyntaxProgram: """Parse the supported command subset into a catalog-independent AST.""" normalized = normalize_spss_source(source) + stripped = normalized.rstrip() + # Termination is checked first, even when the trailing text is a comment. + if not official_v03 and stripped and not stripped.endswith("."): + raise frontend_error( + "spss_syntax_error", "Every command ends with a period.", + span=_span(normalized, len(stripped), len(stripped)), + ) comment = re.search(r"(?m)^[ \t]*\*", normalized) if comment is not None and not official_v03: raise frontend_error( diff --git a/src/openstatspec/sql/capabilities.py b/src/openstatspec/sql/capabilities.py index e6978d7..f4a8436 100644 --- a/src/openstatspec/sql/capabilities.py +++ b/src/openstatspec/sql/capabilities.py @@ -20,9 +20,9 @@ # Release/build automation binds the adapter to the exact language-neutral # specification revision used for normative fixtures and profile semantics. -SPECIFICATION_COMMIT = "864e84479f554b8ee250ffed44c4dfb963750d4a" +SPECIFICATION_COMMIT = "d76121ec343cf9614fb8ad2f8cc50f72ee29966e" SPECIFICATION_STATUS = "released" -SPECIFICATION_RELEASE: str | None = "v0.5.0" +SPECIFICATION_RELEASE: str | None = "v0.6.0" DOLT_WRITE_CONFORMANCE = { "declaration_schema_id": "openstatspec-dolt-adapter-declaration-v1", @@ -590,6 +590,7 @@ def _profile( "adapter_input": "finite_binary64_or_null", "positive_infinity": "reject_before_mutation", "negative_infinity": "reject_before_mutation", + "negative_zero": "reject_before_mutation", "live_bit_exact_evidence": ( "pending_pinned_live_conformance" if dolt_envelope else "profile_conformance_claim" diff --git a/src/openstatspec/sql/inplace_transform.py b/src/openstatspec/sql/inplace_transform.py index eee3566..9390d25 100644 --- a/src/openstatspec/sql/inplace_transform.py +++ b/src/openstatspec/sql/inplace_transform.py @@ -26,6 +26,7 @@ VariableDefinition, VariableSchema, bind_transformation_plan, transformation_plan_from_dict, ) +from ..transform.schema import name_key from .capabilities import effective_profile from .dolt_conformance import DoltConformanceSource from .normative import catalog as core_catalog @@ -438,7 +439,7 @@ def _operand_expression( assert operand.value is not None return literal(_typed_value(operand.value)) assert operand.variable is not None - variable = by_name[operand.variable.casefold()] + variable = by_name[name_key(operand.variable)] return relation.c[str(variable["physical_name"])] @@ -490,12 +491,12 @@ def _apply_plan_on_connection( plan = submission.plan bound = bind_transformation_plan(plan, schema) deleted_names = { - operation.variable.casefold() for operation in plan.operations + name_key(operation.variable) for operation in plan.operations if isinstance(operation, DeleteVariableOperation) } original_deletions = { str(row["variable_id"]): str(row["source_name"]) for row in variables - if str(row["source_name"]).casefold() in deleted_names + if name_key(str(row["source_name"])) in deleted_names } if original_deletions and inspect(connection).has_table("derived_variable_lineage"): lineage = workflow_catalog(MetaData()).derived_variable_lineage @@ -579,7 +580,7 @@ def _apply_plan_on_connection( prefix_output = bind_transformation_plan(prefix, schema).output_schema created = next( variable for variable in prefix_output.variables - if variable.name.casefold() == operation.target.casefold() + if name_key(variable.name) == name_key(operation.target) ) if created.storage_kind != "numeric": unsupported_targets.append(operation.target) @@ -594,7 +595,7 @@ def _apply_plan_on_connection( table_name, MetaData(), schema=dataset.get("physical_table_schema"), autoload_with=connection, ) - by_name = {str(row["source_name"]).casefold(): row for row in variables} + by_name = {name_key(str(row["source_name"])): row for row in variables} used_physical = {str(row["physical_name"]).casefold() for row in variables} next_source_ordinal = max( (int(row["source_ordinal"]) for row in variables), default=0, @@ -696,13 +697,13 @@ def _apply_plan_on_connection( connection.execute(insert(core.variable).values(**created_target)) variables.append(created_target) next_source_ordinal += 1 - by_name[str(created_target["source_name"]).casefold()] = created_target + by_name[name_key(str(created_target["source_name"]))] = created_target _failure_boundary("catalog") if isinstance(operation, CreateVariableOperation): continue if isinstance(operation, RecodeOperation): - source_variable = by_name[operation.source.casefold()] - target_variable = by_name[operation.target.casefold()] + source_variable = by_name[name_key(operation.source)] + target_variable = by_name[name_key(operation.target)] source_column = relation.c[str(source_variable["physical_name"])] target_column = relation.c[str(target_variable["physical_name"])] expression = case( @@ -718,13 +719,13 @@ def _apply_plan_on_connection( connection.execute(update(relation).values({target_column: expression})) _failure_boundary("data") elif isinstance(operation, AssignOperation): - target = by_name[operation.target.casefold()] + target = by_name[name_key(operation.target)] target_column = relation.c[str(target["physical_name"])] value = _operand_expression(operation.value, relation, by_name) connection.execute(update(relation).values({target_column: value})) _failure_boundary("data") elif isinstance(operation, ConditionalAssignOperation): - target = by_name[operation.target.casefold()] + target = by_name[name_key(operation.target)] target_column = relation.c[str(target["physical_name"])] value = _operand_expression(operation.value, relation, by_name) condition = _predicate_expression(operation.condition, relation, by_name) @@ -733,7 +734,7 @@ def _apply_plan_on_connection( ) _failure_boundary("data") elif isinstance(operation, SetVariableLabelOperation): - variable = by_name[operation.variable.casefold()] + variable = by_name[name_key(operation.variable)] connection.execute(update(core.variable).where( core.variable.c.variable_id == variable["variable_id"] ).values(variable_label=operation.label)) @@ -742,12 +743,12 @@ def _apply_plan_on_connection( _replace_value_labels( connection, core=core, - variable=by_name[operation.variable.casefold()], + variable=by_name[name_key(operation.variable)], labels=operation.labels, ) _failure_boundary("catalog") elif isinstance(operation, SetFormatOperation): - variable = by_name[operation.variable.casefold()] + variable = by_name[name_key(operation.variable)] connection.execute(update(core.variable).where( core.variable.c.variable_id == variable["variable_id"] ).values( @@ -760,19 +761,19 @@ def _apply_plan_on_connection( )) _failure_boundary("catalog") elif isinstance(operation, SetMeasurementLevelOperation): - variable = by_name[operation.variable.casefold()] + variable = by_name[name_key(operation.variable)] connection.execute(update(core.variable).where( core.variable.c.variable_id == variable["variable_id"] ).values(measurement_level=operation.level)) _failure_boundary("catalog") elif isinstance(operation, DeleteVariableOperation): - variable = by_name[operation.variable.casefold()] + variable = by_name[name_key(operation.variable)] connection.exec_driver_sql( f"ALTER TABLE {qualified_table} DROP COLUMN " f"{quote(variable['physical_name'])}" ) _delete_variable_metadata(connection, core=core, variable=variable) - by_name.pop(operation.variable.casefold(), None) + by_name.pop(name_key(operation.variable), None) variables = [ row for row in variables if row["variable_id"] != variable["variable_id"] diff --git a/src/openstatspec/sql/profiles.py b/src/openstatspec/sql/profiles.py index 01b914a..5774f5c 100644 --- a/src/openstatspec/sql/profiles.py +++ b/src/openstatspec/sql/profiles.py @@ -273,6 +273,15 @@ def preflight( row_ordinal=row_ordinal, source_name=variable["source_name"], ) + # SQL profiles do not all keep the sign of zero; refuse, never lose it silently. + if value is not None and value == 0 and math.copysign(1.0, value) < 0: + raise _exceeded( + "negative_zero_numeric_value", + f"row {row_ordinal} value for {variable['source_name']!r} " + "is negative zero; negative zero is rejected before mutation.", + row_ordinal=row_ordinal, + source_name=variable["source_name"], + ) row_bytes += 8 continue physical_name = str(variable["physical_name"]) @@ -344,7 +353,10 @@ def _rows_within_limits( if not set(map(type, column)) <= _PLAIN_NUMERIC_TYPES: return False values = np.array(column, dtype=float) # None becomes NaN - if np.isinf(values).any() or np.isnan(values).sum() != column.count(None): + if ( + np.isinf(values).any() or np.isnan(values).sum() != column.count(None) + or np.signbit(values[values == 0]).any() + ): return False row_bytes += 8 statement_bytes += 24 diff --git a/src/openstatspec/transform/plan.py b/src/openstatspec/transform/plan.py index cd31701..5457874 100644 --- a/src/openstatspec/transform/plan.py +++ b/src/openstatspec/transform/plan.py @@ -200,7 +200,11 @@ def __post_init__(self) -> None: if not isinstance(self.unmatched, RecodeResult): _invalid("Recode unmatched behavior must be a typed result.") if self.target_mode == "replace" and self.source != self.target: - _invalid("A replace recode must target its source variable.") + raise frontend_error( + "target_already_exists", + "A replace recode must target its source variable.", + source=self.source, target=self.target, + ) def as_dict(self) -> dict[str, Any]: return { diff --git a/src/openstatspec/transform/schema.py b/src/openstatspec/transform/schema.py index 6a871cb..d6ad42b 100644 --- a/src/openstatspec/transform/schema.py +++ b/src/openstatspec/transform/schema.py @@ -11,6 +11,15 @@ StorageKind = Literal["numeric", "string"] +def name_key(name: str) -> str: + """Case-insensitive variable-name key. + + Unconditional per-code-point lowercase mapping, not case folding: no + context-sensitive mapping such as final sigma applies. + """ + return "".join(character.lower() for character in name) + + @dataclass(frozen=True) class VariableDefinition: name: str @@ -79,7 +88,7 @@ class VariableSchema: variables: tuple[VariableDefinition, ...] def __post_init__(self) -> None: - names = [variable.name.casefold() for variable in self.variables] + names = [name_key(variable.name) for variable in self.variables] if len(names) != len(set(names)): raise ValueError("Variable names must be unique case-insensitively.") diff --git a/src/openstatspec/transform/validation.py b/src/openstatspec/transform/validation.py index 93feea9..31473da 100644 --- a/src/openstatspec/transform/validation.py +++ b/src/openstatspec/transform/validation.py @@ -29,6 +29,7 @@ StorageKind, VariableDefinition, VariableSchema, + name_key, ) @@ -42,7 +43,7 @@ def _expected_type(storage_kind: StorageKind) -> ValueType: def _resolve( variables: dict[str, VariableDefinition], name: str ) -> tuple[str, VariableDefinition]: - key = name.casefold() + key = name_key(name) if key not in variables: raise frontend_error( "unknown_variable", @@ -139,7 +140,7 @@ def _bind_recode( f"Target name {operation.target!r} is reserved.", target=operation.target, ) - target_key = operation.target.casefold() + target_key = name_key(operation.target) if target_key in variables: raise frontend_error( "target_already_exists", @@ -204,26 +205,14 @@ def _validate_predicate( return left_type = _operand_type(predicate.left, variables) right_type = _operand_type(predicate.right, variables) - if left_type != right_type: - raise frontend_error( - "type_mismatch", - "Comparison operands must have the same storage type.", - operator=predicate.operator, - left_type=left_type, - right_type=right_type, - ) - if left_type == "string": + if "string" in (left_type, right_type): raise frontend_error( "expression_type_unsupported", "String comparisons are not supported until exact, " "profile-independent collation semantics are available.", operator=predicate.operator, - ) - if predicate.operator != "=" and left_type != "binary64": - raise frontend_error( - "type_mismatch", - "Ordered comparisons require numeric operands.", - operator=predicate.operator, + left_type=left_type, + right_type=right_type, ) @@ -245,7 +234,7 @@ def _bind_assign( f"Target name {operation.target!r} is reserved.", target=operation.target, ) - target_key = operation.target.casefold() + target_key = name_key(operation.target) if target_key in variables: raise frontend_error( "target_already_exists", @@ -318,7 +307,7 @@ def bind_transformation_plan( raise TypeError("plan must be a TransformationPlan.") if not isinstance(schema, VariableSchema): raise TypeError("schema must be a VariableSchema.") - variables = {variable.name.casefold(): variable for variable in schema.variables} + variables = {name_key(variable.name): variable for variable in schema.variables} last_create = max( (index for index, operation in enumerate(plan.operations) if _creates_variable(operation)), default=-1, @@ -392,7 +381,7 @@ def _bind_create( operation: CreateVariableOperation, variables: dict[str, VariableDefinition], ) -> None: - key = operation.variable.casefold() + key = name_key(operation.variable) if key in variables: raise frontend_error( "target_already_exists", diff --git a/tests/test_cli.py b/tests/test_cli.py index e408845..f3d1060 100755 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -42,11 +42,11 @@ def test_cli_import_inspect_validate_and_export_emit_json(tmp_path, capsys) -> N def test_capability_matrix_is_public_and_cli_matches_engine_boundary(capsys) -> None: matrix = openstatspec.capability_matrix() - assert matrix["adapter_version"] == "0.9.1" + assert matrix["adapter_version"] == "0.10.0" assert matrix["database_io_policy"] == "openstatspec-database-io-v1" assert matrix["specification_status"] == "released" - assert matrix["specification_release"] == "v0.5.0" - assert matrix["specification_commit"] == "864e84479f554b8ee250ffed44c4dfb963750d4a" + assert matrix["specification_release"] == "v0.6.0" + assert matrix["specification_commit"] == "d76121ec343cf9614fb8ad2f8cc50f72ee29966e" assert matrix["directions"] == ["import", "export", "semantic_round_trip"] assert matrix["active_connection"] is None assert matrix["engine"]["package"] == "openstatspec-pyspssio" diff --git a/tests/test_conformance_supplement.py b/tests/test_conformance_supplement.py new file mode 100644 index 0000000..f68894c --- /dev/null +++ b/tests/test_conformance_supplement.py @@ -0,0 +1,360 @@ +"""Conformance Supplement 0.6 manifests; fixtures remain specification-owned.""" + +from copy import deepcopy +import json +import re +import sqlite3 +import struct +from pathlib import Path + +import pandas as pd +import pyspssio +import pytest + +import openstatspec +from conformance import compare_sav_semantics +from openstatspec.frontends.spss import compiler, spss_source_hash +from openstatspec.transform import ( + TransformationFrontendError, TypedValue, ValueLabel, VariableDefinition, + VariableSchema, bind_transformation_plan, transformation_plan_from_dict, +) +from openstatspec.transform.schema import name_key +from test_transform_frontend import _frontend_conformance_manifest + +V03 = compiler.SPSS_FRONTEND_V03_CONTRACT +# Python claims no Frontend 0.1 contract; its default frontend is Frontend 0.2, +# where COMPUTE is a valid command. +SKIPPED = { + "spss-syntax-frontend-0.1-supplement-1.json": { + "reject-frontend-0.2-command": "Python does not claim the Frontend 0.1 contract", + }, +} + + +def _manifest(name: str) -> dict: + root = _frontend_conformance_manifest().parent + return json.loads((root / name).read_text(encoding="utf-8")) + + +def _cases(name: str, key: str = "cases"): + return [ + pytest.param( + case, id=case["id"], + marks=[pytest.mark.skip(reason=SKIPPED[name][case["id"]])] + if case["id"] in SKIPPED.get(name, {}) else [], + ) + for case in _manifest(name)[key] + ] + + +def _assert_compilation(case: dict, compilation) -> None: + expected = case.get("expected_plan", case.get("expected_plan_0_1")) + assert compilation.plan.as_dict() == expected + assert compilation.plan_hash == case["expected_plan_hash"] + if "expected_plan_contract" in case: + assert compilation.plan.contract == case["expected_plan_contract"] + + +def _compile_request(request: dict): + """Run a request through the only JSON request boundary Python has (0.3).""" + return compiler.compile_spss_request({**request, "contract": V03}) + + +def _compile_typed(request: dict): + schema = VariableSchema(tuple( + VariableDefinition( + variable["name"], variable["storage_kind"], + variable_label=variable.get("variable_label"), + value_labels=tuple( + ValueLabel(TypedValue.from_dict(label["value"]), label["label"]) + for label in variable.get("value_labels", []) + ), + ) + for variable in request["input_schema"]["variables"] + )) + return openstatspec.compile_spss_syntax( + request["source_text"], schema, input_alias=request["input_alias"], + ) + + +def _run_frontend_case(case: dict, compile_request) -> None: + request = case["request"] + assert spss_source_hash(request["source_text"]) == case["expected_source_hash"] + # Request validation is owned by the JSON request boundary. + if case["expected_error"] == "request_schema_invalid": + compile_request = _compile_request + if case["expected_error"]: + with pytest.raises(TransformationFrontendError) as caught: + compile_request(request) + assert caught.value.code == case["expected_error"] + return + _assert_compilation(case, compile_request(request)) + + +@pytest.mark.parametrize("case", _cases("spss-syntax-frontend-0.1-supplement-1.json")) +def test_frontend_v01_supplement(case): + # Default frontend path, the one that runs the published 0.1 manifest. + _run_frontend_case(case, _compile_typed) + assert len(_manifest("spss-syntax-frontend-0.1-supplement-1.json")["cases"]) == 16 + + +@pytest.mark.parametrize("case", _cases("spss-syntax-frontend-0.2-supplement-1.json")) +def test_frontend_v02_supplement(case): + _run_frontend_case(case, _compile_typed) + assert len(_manifest("spss-syntax-frontend-0.2-supplement-1.json")["cases"]) == 14 + + +@pytest.mark.parametrize("case", _cases("spss-syntax-frontend-0.3-supplement-1.json")) +def test_frontend_v03_supplement(case): + assert case["request"]["contract"] == V03 + _run_frontend_case(case, compiler.compile_spss_request) + assert len(_manifest("spss-syntax-frontend-0.3-supplement-1.json")["cases"]) == 14 + + +@pytest.mark.parametrize("official", [False, True]) +@pytest.mark.parametrize("source,code", [ + ("RECODE q1 (1 = 0). FOO q1", "spss_syntax_error"), + ("RECODE q1 (1 = 0). EXECUTE", "spss_syntax_error"), + ("IF (q1 = 1) target = q1 + 1.", "expression_type_unsupported"), + ("IF (q1 / 2 = 1) target = 1.", "expression_type_unsupported"), + ("IF (q1 = 1 ** 2) target = 1.", "expression_type_unsupported"), + ("COMPUTE and = 1.", "spss_syntax_error"), + ("IF (q1 = 1) all = 1.", "spss_syntax_error"), + ("VARIABLE LABELS By 'x'.", "spss_syntax_error"), + ("RECODE q1 (1 = 0) INTO GE.", "spss_syntax_error"), + ("COMPUTE target = infinity.", "spss_syntax_error"), + ("IF (q1 = NaN) target = 1.", "spss_syntax_error"), +]) +def test_supplement_frontend_rules_beyond_the_manifests(source, code, official): + schema = VariableSchema(( + VariableDefinition("q1", "numeric"), VariableDefinition("target", "numeric"), + )) + with pytest.raises(TransformationFrontendError) as caught: + openstatspec.compile_spss_syntax( + source, schema, frontend_contract=V03 if official else None, + ) + assert caught.value.code == code + + +def test_name_matching_uses_per_code_point_lowercase(): + assert name_key("\u0391\u03a3") == "\u03b1\u03c3" # no final-sigma context mapping + assert name_key("\u0130") == "i\u0307" # unconditional SpecialCasing mapping + schema = VariableSchema((VariableDefinition("\u03b1\u03c2", "numeric"),)) + with pytest.raises(TransformationFrontendError) as caught: + openstatspec.compile_spss_syntax("VARIABLE LABELS \u0391\u03a3 'x'.", schema) + assert caught.value.code == "unknown_variable" + + +@pytest.mark.parametrize("name", [ + "transformation-plan-0.1-supplement-1.json", + "transformation-plan-0.2-supplement-1.json", +]) +def test_plan_supplements(name): + for case in _manifest(name)["cases"]: + if case["expected_error"]: + with pytest.raises(TransformationFrontendError) as caught: + transformation_plan_from_dict(case["plan"]) + assert caught.value.code == case["expected_error"], case["id"] + continue + assert transformation_plan_from_dict(case["plan"]).sha256() == case["expected_plan_hash"] + + +def test_plan_binding_refuses_string_variable_compared_with_number(): + plan = transformation_plan_from_dict({ + "contract": "openstatspec-transformation-plan-v0.2", "input_alias": "parent", + "operations": [{ + "op": "conditional_assign", "target": "target", + "condition": { + "expression": "comparison", "operator": "=", + "left": {"kind": "variable", "variable": "color"}, + "right": {"kind": "literal", "value": {"type": "binary64", "bits": "3ff0000000000000"}}, + }, + "value": {"kind": "literal", "value": {"type": "binary64", "bits": "3ff0000000000000"}}, + }], + }) + schema = VariableSchema(( + VariableDefinition("color", "string"), VariableDefinition("target", "numeric"), + )) + with pytest.raises(TransformationFrontendError) as caught: + bind_transformation_plan(plan, schema) + assert caught.value.code == "expression_type_unsupported" + + +@pytest.mark.parametrize("case", _cases("in-place-transformation-0.1-supplement-1.json")) +def test_in_place_v01_supplement_on_sqlite(case, tmp_path): + assert case["database_profile"] == "sqlite" + path = tmp_path / "supplement.sqlite" + url = f"sqlite:///{path}" + source = tmp_path / "survey.sav" + pyspssio.write_sav(str(source), pd.DataFrame({"q1": [1.0, 2.0, None]})) + openstatspec.initialize_catalog(database_url=url) + openstatspec.import_sav(source, database_url=url, dataset_id="survey") + openstatspec.install_in_place_transformation_schema(database_url=url) + connection = sqlite3.connect(path) + + def state(): + dataset_id, schema, table = connection.execute( + "SELECT dataset_id, physical_table_schema, physical_table_name FROM dataset" + ).fetchone() + tables = [row[0] for row in connection.execute( + "SELECT name FROM sqlite_master WHERE type IN ('table', 'view')" + )] + return { + "dataset_id": dataset_id, "physical_table_schema": schema, + "physical_table_name": table, + "dataset_count": connection.execute("SELECT COUNT(*) FROM dataset").fetchone()[0], + "persistent_data_table_count": sum(name.startswith("data_") for name in tables), + }, set(tables) + + before, tables_before = state() + assert before["physical_table_schema"] == case["before"]["physical_table_schema"] + assert before["dataset_count"] == case["before"]["dataset_count"] + assert before["persistent_data_table_count"] == case["before"]["persistent_data_table_count"] + openstatspec.apply_spss_in_place( + database_url=url, dataset_id=before["dataset_id"], actor="supplement", + source_text=case["source_text"], + ) + after, tables_after = state() + expected = case["after"] + assert after == {**before, **{ + key: expected[key] for key in ( + "physical_table_schema", "dataset_count", "persistent_data_table_count", + ) + }} + assert tables_after == tables_before + target = expected["created_target"] + assert connection.execute( + "SELECT storage_kind FROM variable WHERE source_name = ?", (target,) + ).fetchone() == (expected["created_target_storage_kind"],) + physical = connection.execute( + "SELECT physical_name FROM variable WHERE source_name = ?", (target,) + ).fetchone()[0] + values = connection.execute( + f'SELECT "{physical}" FROM "{after["physical_table_name"]}"' + ).fetchall() + assert expected["created_target_all_system_missing"] is True + assert values and all(value is None for (value,) in values) + audit = dict(zip( + case["required_audit_fields"], + connection.execute( + f"SELECT {', '.join(case['required_audit_fields'])} FROM transformation_apply" + ).fetchone(), + )) + assert audit["physical_table_schema"] == expected["audit_physical_table_schema"] + assert audit["dataset_id"] == after["dataset_id"] + assert audit["status"] == "succeeded" + + +def _bits(value) -> str | None: + return None if value is None else struct.pack(">d", value).hex() + + +def _generated_fixture(path: Path, bits: list[str]) -> Path: + """Write a runner-generated supplement fixture as fixtures/README.md states.""" + values = [struct.unpack(">d", bytes.fromhex(item))[0] for item in bits] + pyspssio.write_sav( + str(path), pd.DataFrame({"value": values}), + metadata={"var_formats": {"value": "F8.2"}}, + ) + frame, _ = pyspssio.read_sav(str(path)) + assert [_bits(value) for value in frame["value"]] == bits + return path + + +GENERATED = { + "fixtures/negative-zero.sav": ["0000000000000000", "8000000000000000", "3ff0000000000000"], + "fixtures/nan.sav": ["3ff0000000000000", "7ff8000000000000", "4000000000000000"], +} + + +def _attribute_names(attributes: dict) -> list[str]: + names = [re.sub(r"\[[0-9]+\]$", "", name) for name in attributes] + return list(dict.fromkeys(names)) + + +@pytest.mark.parametrize("fixture", _cases("spss-sav-zsav-1.0-supplement-1.json", "fixtures")) +def test_sav_supplement_on_sqlite(fixture, tmp_path): + root = _frontend_conformance_manifest().parent + path = tmp_path / "catalog.sqlite" + url = f"sqlite:///{path}" + openstatspec.initialize_catalog(database_url=url) + source = ( + _generated_fixture(tmp_path / Path(fixture["source"]).name, GENERATED[fixture["source"]]) + if fixture["source"] in GENERATED else root / fixture["source"] + ) + expects = set(fixture["expects"]) + expected = fixture.get("expected_catalog", {}) + + if expects == {"negative_zero_preserved_refused_or_reported"}: + # Python refuses negative zero before mutation on every SQL profile. + assert openstatspec.capability_matrix()["sql_profiles"]["sqlite"][ + "numeric_value_policy"]["negative_zero"] == "reject_before_mutation" + with pytest.raises(Exception, match="negative zero"): + openstatspec.import_sav(source, database_url=url, dataset_id="special") + connection = sqlite3.connect(path) + assert connection.execute("SELECT COUNT(*) FROM dataset").fetchone() == (0,) + assert connection.execute( + "SELECT event_code FROM fidelity_event WHERE source_item = ?", (source.name,) + ).fetchall() == [("target_capability_exceeded",)] + return + + openstatspec.import_sav(source, database_url=url, dataset_id="supplement") + connection = sqlite3.connect(path) + connection.row_factory = sqlite3.Row + dataset = dict(connection.execute("SELECT * FROM dataset").fetchone()) + if "dataset_spec_version" in expects: + assert dataset["spec_version"] == expected["dataset"]["spec_version"] + if "catalog_schema_version" in expects: + identity = dict(connection.execute( + "SELECT contract_id, schema_version FROM catalog_identity" + ).fetchone()) + assert identity == expected["catalog_identity"] + if "physical_table_schema_rule" in expects: + assert dataset["physical_table_schema"] is None + if "variables" in expected: + for item in expected["variables"]: + row = dict(connection.execute( + "SELECT * FROM variable WHERE source_name = ?", (item["variable"],) + ).fetchone()) + assert {key: row[key] for key in item if key != "variable"} == { + key: value for key, value in item.items() if key != "variable" + } + if "multiple_response_sets" in expected: + for item in expected["multiple_response_sets"]: + row = dict(connection.execute( + "SELECT * FROM multiple_response_set WHERE set_name = ?", (item["name"],) + ).fetchone()) + assert {key: row[key] for key in item if key != "name"} == { + key: value for key, value in item.items() if key != "name" + } + if "missing_rules" in expected: + for item in expected["missing_rules"]: + row = dict(connection.execute( + "SELECT m.* FROM missing_rule m JOIN variable v USING (variable_id) " + "WHERE v.source_name = ? AND m.ordinal = ?", + (item["variable"], item["ordinal"]), + ).fetchone()) + assert {key: row[key] for key in item if key != "variable"} == { + key: value for key, value in item.items() if key != "variable" + } + if expects == {"nan_preserved_refused_or_declared_null"}: + assert openstatspec.capability_matrix()["sql_profiles"]["sqlite"][ + "numeric_value_policy"]["spss_nan"] == "canonicalize_to_sql_null_during_spss_decode" + values = connection.execute( + f'SELECT value FROM "{dataset["physical_table_name"]}" ORDER BY __case_ordinal' + ).fetchall() + assert [_bits(row[0]) for row in values] == ["3ff0000000000000", None, "4000000000000000"] + + if "semantic_round_trip" in fixture["directions"] or "export" in fixture["directions"]: + destination = tmp_path / f"exported{source.suffix}" + openstatspec.export_sav( + database_url=url, dataset_id="supplement", destination=destination, + allow_loss=["compatible-variable-names-not-preserved"], + ) + assert compare_sav_semantics(source, destination)["equivalent"] is True + if "attribute_export_order" in expects: + _, metadata = pyspssio.read_sav(str(destination)) + assert _attribute_names(metadata["file_attributes"]) == expected[ + "dataset_attribute_export_order"] + for item in expected["variable_attribute_export_order"]: + assert _attribute_names(metadata["var_attributes"][item["variable"]]) == item["names"] diff --git a/tests/test_frontend_v03.py b/tests/test_frontend_v03.py index 8772221..2b2a9fd 100644 --- a/tests/test_frontend_v03.py +++ b/tests/test_frontend_v03.py @@ -114,7 +114,7 @@ def test_request_boundary_rejects_wrong_fields_and_types(path, value): target[path[-1]] = value with pytest.raises(openstatspec.TransformationFrontendError) as caught: compiler.compile_spss_request(request) - assert caught.value.code == "invalid_spss_request" + assert caught.value.code == "request_schema_invalid" def test_grouped_commands_and_comments_preserve_order_and_metadata(): @@ -175,7 +175,7 @@ def test_official_expansion_does_not_change_default_rejections(source): ("VARIABLE LEVEL / a (NOMINAL).", "spss_syntax_error"), ("FORMATS a TO c TO b (F8.0).", "invalid_variable_range"), ("/* outer /* inner */ */ EXECUTE.", "spss_syntax_error"), - ("COMPUTE a = 1 * not a comment.", "spss_syntax_error"), + ("COMPUTE a = 1 * not a comment.", "expression_type_unsupported"), ("COMMENT unterminated", "spss_syntax_error"), ("EXECUTE. VALUE LABELS.", "spss_syntax_error"), ("EXECUTE. ADD VALUE LABELS.", "spss_syntax_error"), @@ -223,5 +223,5 @@ def test_request_metadata_uses_schema_fields_without_coercion_or_loss(): def test_request_requires_every_contract_field(missing): request = _request() del request[missing] - with pytest.raises(openstatspec.TransformationFrontendError, match="invalid_spss_request"): + with pytest.raises(openstatspec.TransformationFrontendError, match="request_schema_invalid"): openstatspec.compile_spss_request(request) diff --git a/tests/test_sql_profiles.py b/tests/test_sql_profiles.py index 4ff870d..3afb4b9 100755 --- a/tests/test_sql_profiles.py +++ b/tests/test_sql_profiles.py @@ -32,10 +32,10 @@ def test_profile_detection_tracks_supported_dialect_urls() -> None: def test_profile_declarations_publish_released_specification_provenance() -> None: for declaration in capabilities.profile_declarations().values(): assert declaration["specification_status"] == "released" - assert declaration["specification_release"] == "v0.5.0" + assert declaration["specification_release"] == "v0.6.0" assert ( declaration["specification_commit"] - == "864e84479f554b8ee250ffed44c4dfb963750d4a" + == "d76121ec343cf9614fb8ad2f8cc50f72ee29966e" ) def test_profile_preflight_fails_without_transforming_a_wide_dataset() -> None: diff --git a/tests/test_transform_frontend.py b/tests/test_transform_frontend.py index 2edc70f..2bc2817 100644 --- a/tests/test_transform_frontend.py +++ b/tests/test_transform_frontend.py @@ -451,7 +451,7 @@ def test_arbitrary_sql_and_python_sources_fail_closed() -> None: schema = _schema(VariableDefinition("q1", "numeric")) assert _error( "SELECT * FROM q1.", schema, - ).code == "spss_syntax_error" + ).code == "unsupported_spss_command" assert _error( "PYTHON PROGRAM.", schema, ).code == "unsupported_spss_command"