Skip to content

Commit 98ffb4b

Browse files
committed
Write normative OpenStatSpec catalog
1 parent e38361f commit 98ffb4b

8 files changed

Lines changed: 695 additions & 19 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,12 @@ The normative model lives in the `OpenStatSpec/specification` repository.
88
## Boundaries
99

1010
For each supported import, one source dataset becomes one dedicated wide SQL
11-
table. Cases are rows and source variables are physical SQL columns. Catalog
12-
metadata is stored separately. The adapter does not reshape data, create EAV
11+
table. Cases are rows and source variables are physical SQL columns. The
12+
singular UUID-keyed tables from the specification (`dataset`, `variable`,
13+
`operation`, `fidelity_event`, and related metadata tables) are the public
14+
catalog contract. Historical `*_catalog` tables are an internal compatibility
15+
layer for the current exporter and are not the standard database interface.
16+
The adapter does not reshape data, create EAV
1317
or long-form tables, or harmonize studies or waves.
1418

1519
Unsupported source features, SQL targets, or export paths fail explicitly.

‎docs/release-readiness.md‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@ Creating a version tag remains a separate maintainer action.
66
## Supported workflow
77

88
For a supported unencrypted SAV or ZSAV source, the adapter imports one source
9-
dataset into exactly one dedicated wide data table plus catalog tables. It can
10-
validate that representation and export it back to SAV or ZSAV.
9+
dataset into exactly one dedicated wide data table plus the complete singular,
10+
UUID-keyed normative catalog from the SPSS profile. It can validate that
11+
representation and export it back to SAV or ZSAV. Historical `*_catalog`
12+
tables remain private compatibility storage and do not replace the normative
13+
database contract.
1114

1215
## SQL profiles
1316

@@ -28,11 +31,12 @@ diagnostics. An export with known loss fails unless the caller passes the
2831
relevant diagnostic codes through `allow_loss` or repeats `--allow-loss CODE`
2932
in the CLI.
3033

31-
The concrete pyspssio boundaries are documented in the [SAV profile](sav-profile.md):
32-
document text is unobservable; file labels are preserved by the pinned fork, legacy compatible names are fail-closed
33-
on export, and only UTF-8 has a source-encoding fidelity contract. Separate
34-
print/write formats, variable sets, multiple-response sets, alignment, scalar
35-
attributes, and ordered custom-attribute arrays have verified paths. A caller
34+
The concrete pyspssio boundaries are documented in the [SAV profile](sav-profile.md).
35+
The pinned OpenStatSpec fork preserves document text, file labels, legacy
36+
compatible names, separate print/write formats, variable sets,
37+
multiple-response sets, alignment, scalar attributes, and ordered
38+
custom-attribute arrays. Non-UTF-8 output requires an explicit matching locale;
39+
otherwise the strict export policy reports and blocks the loss. A caller
3640
that supplies consent for an available loss code receives the
3741
machine-readable loss report with the export result.
3842

‎src/openstatspec/sql/normative.py‎

Lines changed: 443 additions & 0 deletions
Large diffs are not rendered by default.

‎src/openstatspec/sql/wide.py‎

Lines changed: 75 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@
1313
from sqlalchemy.dialects import mysql, postgresql, sqlite
1414
from ..core import UnsupportedOperationError
1515
from .profiles import preflight, validate_connection_url
16+
from .normative import (
17+
catalog as normative_catalog,
18+
create as create_normative_catalog,
19+
dataset_id_for_name as normative_dataset_id_for_name,
20+
finish_operation as finish_normative_operation,
21+
record_fidelity_events as record_normative_fidelity_events,
22+
record_operation as record_normative_operation,
23+
store_imported_dataset as store_normative_dataset,
24+
)
1625

1726
_IDENTIFIER = re.compile(r"[^a-zA-Z0-9_]+")
1827

@@ -187,28 +196,42 @@ def _event_rows(
187196
def _record_failed_preflight(
188197
*, engine: Any, metadata: MetaData, datasets: Table, variable_catalog: Table,
189198
multiple_response_catalog: Table, fidelity_event_catalog: Table,
190-
operation_catalog: Table, operation_id: str, source_name: str,
191-
variable_count: int, profile_name: str, error: Exception,
199+
operation_catalog: Table, normative: Any, operation_id: str, source_name: str,
200+
source_format: str, variable_count: int, profile_name: str, error: Exception,
192201
) -> None:
193202
"""Persist a failed preflight without creating any source dataset state."""
194203
with engine.begin() as connection:
195204
metadata.create_all(connection, tables=[
196205
datasets, variable_catalog, multiple_response_catalog,
197206
fidelity_event_catalog, operation_catalog,
198207
])
208+
create_normative_catalog(connection, normative)
209+
failed_at = datetime.now(UTC).replace(tzinfo=None)
210+
record_normative_operation(
211+
connection, normative, operation_id=operation_id,
212+
operation_kind="import", status="failed", source_format=source_format,
213+
started_at=failed_at, completed_at=failed_at,
214+
)
199215
connection.execute(insert(operation_catalog).values(
200216
operation_id=operation_id, direction="import", status="failed", dataset_id=None,
201217
source=source_name, created_at=_now(), completed_at=_now(),
202218
details=json.dumps({"reason": "preflight", "variable_count": variable_count,
203219
"capability": getattr(error, "details", {})}, sort_keys=True),
204220
))
221+
failed_events = ({
222+
"code": getattr(error, "code", "target-capability-exceeded"),
223+
"detail": str(error), "severity": "error", "source_item": source_name,
224+
"details": {"variable_count": variable_count, "profile": profile_name,
225+
**getattr(error, "details", {})},
226+
},)
205227
connection.execute(insert(fidelity_event_catalog), _event_rows(
206-
operation_id=operation_id, dataset_id=None, direction="import", fidelity_events=({
207-
"code": getattr(error, "code", "target-capability-exceeded"), "detail": str(error), "severity": "error",
208-
"details": {"variable_count": variable_count, "profile": profile_name,
209-
**getattr(error, "details", {})},
210-
},),
228+
operation_id=operation_id, dataset_id=None, direction="import",
229+
fidelity_events=failed_events,
211230
))
231+
record_normative_fidelity_events(
232+
connection, normative, operation_id=operation_id, dataset_id=None,
233+
direction="import", events=failed_events,
234+
)
212235

213236
def multiple_response_set_catalog(metadata: MetaData) -> Table:
214237
return Table(
@@ -743,10 +766,12 @@ def create_wide_dataset(
743766
engine = create_engine(database_url)
744767
metadata = MetaData()
745768
datasets, variable_catalog, fidelity_event_catalog, operation_catalog = catalog(metadata)
769+
normative = normative_catalog(metadata)
746770
multiple_response_catalog = multiple_response_set_catalog(metadata)
747771
source_extensions_catalog = source_extension_catalog(metadata)
748772
documents_catalog, value_labels_catalog, missing_rules_catalog, attributes_catalog = normalized_metadata_tables(metadata)
749773
operation_id = str(uuid4())
774+
fidelity_events = tuple(fidelity_events)
750775
try:
751776
preflight(profile, variables)
752777
validate_spss_catalog(
@@ -759,8 +784,9 @@ def create_wide_dataset(
759784
engine=engine, metadata=metadata, datasets=datasets,
760785
variable_catalog=variable_catalog, multiple_response_catalog=multiple_response_catalog,
761786
fidelity_event_catalog=fidelity_event_catalog, operation_catalog=operation_catalog,
762-
operation_id=operation_id, source_name=source_name, variable_count=len(variables),
763-
profile_name=profile.name, error=error,
787+
operation_id=operation_id, source_name=source_name,
788+
source_format=source_format, variable_count=len(variables),
789+
profile_name=profile.name, error=error, normative=normative,
764790
)
765791
raise
766792
data_table = Table(
@@ -771,7 +797,12 @@ def create_wide_dataset(
771797
)
772798
with engine.begin() as connection:
773799
metadata.create_all(connection, tables=[datasets, variable_catalog, multiple_response_catalog, source_extensions_catalog, documents_catalog, value_labels_catalog, missing_rules_catalog, attributes_catalog, fidelity_event_catalog, operation_catalog])
800+
create_normative_catalog(connection, normative)
774801
_migrate_catalog_columns(connection, datasets, variable_catalog, multiple_response_catalog)
802+
record_normative_operation(
803+
connection, normative, operation_id=operation_id,
804+
operation_kind="import", status="started", source_format=source_format,
805+
)
775806
connection.execute(insert(operation_catalog).values(
776807
operation_id=operation_id, direction="import", status="running", dataset_id=dataset_id,
777808
source=source_name, created_at=_now(), details=json.dumps({"variable_count": len(variables), **dict(operation_details or {})}, sort_keys=True),
@@ -821,6 +852,22 @@ def create_wide_dataset(
821852
)
822853
if event_rows:
823854
connection.execute(insert(fidelity_event_catalog), event_rows)
855+
normative_dataset_id = store_normative_dataset(
856+
connection, normative, dataset_name=dataset_id,
857+
source_format=source_format, physical_table_name=data_table.name,
858+
dataset_label=file_label, source_encoding=source_encoding,
859+
source_hash=source_sha256, source_case_count=len(materialized),
860+
imported_at=imported_at or None, variables=variables,
861+
documents=docs_rows, value_labels=labels_rows,
862+
missing_rules=missing_rows, attributes=attributes_rows,
863+
multiple_response_sets=mrset_rows,
864+
source_extensions=source_extensions or {},
865+
)
866+
record_normative_fidelity_events(
867+
connection, normative, operation_id=operation_id,
868+
dataset_id=normative_dataset_id, direction="import",
869+
events=fidelity_events,
870+
)
824871
if materialized:
825872
try:
826873
connection.execute(insert(data_table), materialized)
@@ -840,6 +887,9 @@ def create_wide_dataset(
840887
connection.execute(update(operation_catalog).where(operation_catalog.c.operation_id == operation_id).values(
841888
status="succeeded", completed_at=_now(),
842889
))
890+
finish_normative_operation(
891+
connection, normative, operation_id=operation_id, status="succeeded",
892+
)
843893
return {"dataset_id": dataset_id, "data_table": data_table.name, "case_count": len(materialized), "operation_id": operation_id}
844894

845895

@@ -965,11 +1015,20 @@ def record_export_operation(
9651015
engine = create_engine(database_url)
9661016
metadata = MetaData()
9671017
datasets, variables, fidelity_events, operations = catalog(metadata)
1018+
normative = normative_catalog(metadata)
9681019
multiple_response = multiple_response_set_catalog(metadata)
9691020
operation_id = str(uuid4())
9701021
events = tuple(allowed_fidelity_events)
9711022
with engine.begin() as connection:
9721023
metadata.create_all(connection, tables=[datasets, variables, multiple_response, fidelity_events, operations])
1024+
create_normative_catalog(connection, normative)
1025+
normative_dataset_id = normative_dataset_id_for_name(connection, normative, dataset_id)
1026+
completed_at = datetime.now(UTC).replace(tzinfo=None)
1027+
record_normative_operation(
1028+
connection, normative, operation_id=operation_id,
1029+
operation_kind="export", status="succeeded", source_format=None,
1030+
started_at=completed_at, completed_at=completed_at,
1031+
)
9731032
connection.execute(insert(operations).values(
9741033
operation_id=operation_id, direction="export", status="succeeded", dataset_id=dataset_id,
9751034
destination=destination, created_at=_now(), completed_at=_now(),
@@ -983,6 +1042,13 @@ def record_export_operation(
9831042
)
9841043
if rows:
9851044
connection.execute(insert(fidelity_events), rows)
1045+
record_normative_fidelity_events(
1046+
connection, normative, operation_id=operation_id,
1047+
dataset_id=normative_dataset_id, direction="export",
1048+
events=({**event, "severity": event.get("severity", "warning"),
1049+
"details": {**event.get("details", {}), "accepted_by_user": True}}
1050+
for event in events),
1051+
)
9861052
return operation_id
9871053

9881054
def validate_wide_dataset(*, database_url: str, dataset_id: str) -> dict[str, Any]:

‎tests/test_normative_catalog.py‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import json
2+
import sqlite3
3+
from uuid import UUID
4+
5+
from openstatspec.sql.wide import create_wide_dataset, record_export_operation
6+
7+
8+
NORMATIVE_TABLES = {
9+
"dataset", "operation", "variable", "value_label_set", "value_label",
10+
"variable_value_label_set", "missing_rule", "dataset_attribute",
11+
"variable_attribute", "document", "variable_set", "variable_set_member",
12+
"multiple_response_set", "multiple_response_member", "fidelity_event",
13+
}
14+
15+
16+
def variables():
17+
return [
18+
{
19+
"ordinal": 1, "source_name": "answer", "physical_name": "answer",
20+
"storage_kind": "numeric", "string_width": None, "label": "Answer",
21+
"format": "F8.0", "print_format": "[5, 8, 0]",
22+
"write_format": "[5, 12, 2]", "measure": "nominal",
23+
"role": "input", "alignment": "right", "display_width": 12,
24+
"attributes": "{}", "compat_name": None,
25+
"value_labels": json.dumps({"1.0": "Yes", "2.0": "No"}),
26+
"missing_ranges": json.dumps([{"lo": -99.0, "hi": -1.0}, 999.0]),
27+
},
28+
{
29+
"ordinal": 2, "source_name": "comment", "physical_name": "comment",
30+
"storage_kind": "string", "string_width": 40, "label": "Comment",
31+
"format": "A40", "print_format": "[1, 40, 0]",
32+
"write_format": "[1, 40, 0]", "measure": "nominal",
33+
"role": "target", "alignment": "left", "display_width": 40,
34+
"attributes": "{}", "compat_name": None,
35+
"value_labels": "{}", "missing_ranges": "[]",
36+
},
37+
]
38+
39+
40+
def test_import_writes_complete_normative_catalog(tmp_path):
41+
database_path = tmp_path / "normative.sqlite"
42+
database_url = f"sqlite:///{database_path}"
43+
result = create_wide_dataset(
44+
database_url=database_url, dataset_id="wave_1",
45+
source_name="fixture.sav", source_format="SAV",
46+
rows=[{"answer": 1.0, "comment": "hello"}], variables=variables(),
47+
file_label="Fixture", source_encoding="UTF-8", source_sha256="abc123",
48+
documents=json.dumps(["first document"]),
49+
file_attributes=json.dumps({"Source": ["one", "two"]}),
50+
file_attribute_values={"Source": ["one", "two"]},
51+
variable_attribute_values={"answer": {"Origin": "fixture"}},
52+
multiple_response_sets=json.dumps({
53+
"$answers": {"counted_value": 1.0, "variable_list": ["answer"]},
54+
}),
55+
source_extensions={"spss.variable_sets": {"Analysis": ["answer", "comment"]}},
56+
fidelity_events=[{
57+
"code": "fixture-warning", "detail": "Synthetic diagnostic",
58+
"source_item": "answer", "details": {"test": True},
59+
}],
60+
)
61+
connection = sqlite3.connect(database_path)
62+
table_names = {
63+
row[0] for row in connection.execute(
64+
"select name from sqlite_master where type = 'table'"
65+
)
66+
}
67+
assert NORMATIVE_TABLES <= table_names
68+
69+
dataset = connection.execute(
70+
"select dataset_id, spec_version, source_format, physical_table_name, "
71+
"dataset_name, dataset_label, source_encoding, source_hash, source_case_count, imported_at "
72+
"from dataset"
73+
).fetchone()
74+
UUID(dataset[0])
75+
assert dataset[1:-1] == (
76+
"1.0", "SAV", "data_wave_1", "wave_1", "Fixture", "UTF-8", "abc123", 1,
77+
)
78+
assert dataset[-1]
79+
80+
variable_rows = connection.execute(
81+
"select source_ordinal, source_name, physical_name, storage_kind, "
82+
"declared_string_width, variable_label, print_format_family, print_format_width, "
83+
"print_format_decimals, write_format_family, write_format_width, "
84+
"write_format_decimals, measurement_level, variable_role, display_width, "
85+
"display_alignment from variable order by source_ordinal"
86+
).fetchall()
87+
assert variable_rows == [
88+
(1, "answer", "answer", "numeric", None, "Answer", "5", 8, 0, "5", 12, 2, "nominal", "input", 12, "right"),
89+
(2, "comment", "comment", "string", 40, "Comment", "1", 40, 0, "1", 40, 0, "nominal", "target", 40, "left"),
90+
]
91+
assert connection.execute("select numeric_code, label from value_label order by ordinal").fetchall() == [(1.0, "Yes"), (2.0, "No")]
92+
assert connection.execute("select rule_kind, numeric_lower, numeric_upper, numeric_value from missing_rule order by ordinal").fetchall() == [("numeric_range", -99.0, -1.0, None), ("discrete", None, None, 999.0)]
93+
assert connection.execute("select attribute_name, array_ordinal, attribute_value from dataset_attribute order by array_ordinal").fetchall() == [("Source", 1, "one"), ("Source", 2, "two")]
94+
assert connection.execute("select attribute_name, array_ordinal, attribute_value from variable_attribute").fetchall() == [("Origin", 1, "fixture")]
95+
assert connection.execute("select source_ordinal, document_text from document").fetchall() == [(1, "first document")]
96+
assert connection.execute("select set_name from variable_set").fetchall() == [("Analysis",)]
97+
assert connection.execute("select source_ordinal from variable_set_member order by source_ordinal").fetchall() == [(1,), (2,)]
98+
assert connection.execute("select set_name, set_kind, counted_numeric_value from multiple_response_set").fetchall() == [("$answers", "MD", 1.0)]
99+
assert connection.execute("select source_ordinal from multiple_response_member").fetchall() == [(1,)]
100+
assert connection.execute(
101+
"select operation_kind, status, source_format, started_at is not null, completed_at is not null "
102+
"from operation where operation_id = ?", (result["operation_id"],),
103+
).fetchone() == ("import", "succeeded", "SAV", 1, 1)
104+
event = connection.execute(
105+
"select dataset_id, direction, severity, event_code, source_item, detail_json, created_at "
106+
"from fidelity_event where operation_id = ?", (result["operation_id"],),
107+
).fetchone()
108+
assert event[:5] == (dataset[0], "import", "warning", "fixture-warning", "answer")
109+
assert json.loads(event[5]) == {"message": "Synthetic diagnostic", "test": True}
110+
assert event[6]
111+
112+
export_id = record_export_operation(
113+
database_url=database_url, dataset_id="wave_1", destination="out.sav",
114+
allowed_fidelity_events=[{
115+
"code": "export-warning", "detail": "Accepted", "source_item": "comment",
116+
}],
117+
)
118+
assert connection.execute(
119+
"select operation_kind, status from operation where operation_id = ?", (export_id,),
120+
).fetchone() == ("export", "succeeded")
121+
export_event = connection.execute(
122+
"select dataset_id, direction, event_code, source_item, detail_json "
123+
"from fidelity_event where operation_id = ?", (export_id,),
124+
).fetchone()
125+
assert export_event[:4] == (dataset[0], "export", "export-warning", "comment")
126+
assert json.loads(export_event[4])["accepted_by_user"] is True

0 commit comments

Comments
 (0)