ambers 0.4.2__tar.gz → 0.4.5__tar.gz

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.
Files changed (90) hide show
  1. {ambers-0.4.2 → ambers-0.4.5}/.github/workflows/ci.yml +1 -1
  2. {ambers-0.4.2 → ambers-0.4.5}/.gitignore +1 -0
  3. {ambers-0.4.2 → ambers-0.4.5}/CHANGELOG.md +32 -0
  4. {ambers-0.4.2 → ambers-0.4.5}/Cargo.lock +1 -1
  5. {ambers-0.4.2 → ambers-0.4.5}/Cargo.toml +1 -1
  6. {ambers-0.4.2 → ambers-0.4.5}/PKG-INFO +34 -1
  7. {ambers-0.4.2 → ambers-0.4.5}/README.md +33 -0
  8. {ambers-0.4.2 → ambers-0.4.5}/pyproject.toml +1 -1
  9. {ambers-0.4.2 → ambers-0.4.5}/python/ambers/__init__.py +4 -0
  10. {ambers-0.4.2 → ambers-0.4.5}/python/ambers/__init__.pyi +23 -2
  11. {ambers-0.4.2 → ambers-0.4.5}/python/ambers/_containers.py +11 -1
  12. {ambers-0.4.2 → ambers-0.4.5}/python/ambers/_io.py +11 -3
  13. ambers-0.4.5/python/ambers/_warnings.py +44 -0
  14. ambers-0.4.5/python/ambers/codebook/__init__.py +330 -0
  15. ambers-0.4.5/python/ambers/codebook/_engine.py +304 -0
  16. ambers-0.4.5/python/ambers/codebook/_types.py +382 -0
  17. {ambers-0.4.2 → ambers-0.4.5}/src/columnar.rs +84 -22
  18. {ambers-0.4.2 → ambers-0.4.5}/src/compression/bytecode.rs +84 -14
  19. {ambers-0.4.2 → ambers-0.4.5}/src/compression/zlib.rs +1 -1
  20. {ambers-0.4.2 → ambers-0.4.5}/src/dictionary.rs +99 -3
  21. {ambers-0.4.2 → ambers-0.4.5}/src/document.rs +1 -1
  22. {ambers-0.4.2 → ambers-0.4.5}/src/error.rs +6 -0
  23. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/long_string_labels.rs +1 -1
  24. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/long_string_missing.rs +1 -1
  25. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/var_display.rs +1 -1
  26. {ambers-0.4.2 → ambers-0.4.5}/src/io_utils.rs +18 -0
  27. {ambers-0.4.2 → ambers-0.4.5}/src/lib.rs +4 -2
  28. {ambers-0.4.2 → ambers-0.4.5}/src/metadata.rs +6 -0
  29. {ambers-0.4.2 → ambers-0.4.5}/src/python/io.rs +2 -1
  30. {ambers-0.4.2 → ambers-0.4.5}/src/python/metadata.rs +16 -0
  31. {ambers-0.4.2 → ambers-0.4.5}/src/scanner.rs +86 -12
  32. {ambers-0.4.2 → ambers-0.4.5}/src/value_labels.rs +2 -2
  33. {ambers-0.4.2 → ambers-0.4.5}/src/variable.rs +35 -10
  34. ambers-0.4.5/tests/test_codebook.py +385 -0
  35. ambers-0.4.5/tests/test_codebook_engine.py +238 -0
  36. ambers-0.4.5/tests/test_codebook_types.py +358 -0
  37. ambers-0.4.5/tests/test_malformed.py +118 -0
  38. ambers-0.4.5/tests/test_malformed.rs +658 -0
  39. ambers-0.4.5/tests/test_polars_compat.py +162 -0
  40. ambers-0.4.5/tests/test_warnings.py +227 -0
  41. {ambers-0.4.2 → ambers-0.4.5}/tests/test_writer_issues.py +2 -1
  42. ambers-0.4.5/warnings_and_errors.md +108 -0
  43. {ambers-0.4.2 → ambers-0.4.5}/.cargo/config.toml +0 -0
  44. {ambers-0.4.2 → ambers-0.4.5}/.github/workflows/release.yml +0 -0
  45. {ambers-0.4.2 → ambers-0.4.5}/LICENSE +0 -0
  46. {ambers-0.4.2 → ambers-0.4.5}/apply_labels.md +0 -0
  47. {ambers-0.4.2 → ambers-0.4.5}/images/ambers-banner-v2.svg +0 -0
  48. {ambers-0.4.2 → ambers-0.4.5}/images/ambers-banner.svg +0 -0
  49. {ambers-0.4.2 → ambers-0.4.5}/metadata.md +0 -0
  50. {ambers-0.4.2 → ambers-0.4.5}/python/ambers/_missing.py +0 -0
  51. {ambers-0.4.2 → ambers-0.4.5}/python/ambers/_transforms.py +0 -0
  52. {ambers-0.4.2 → ambers-0.4.5}/python/ambers/_validate.py +0 -0
  53. {ambers-0.4.2 → ambers-0.4.5}/src/arrow_convert.rs +0 -0
  54. {ambers-0.4.2 → ambers-0.4.5}/src/compression/bytecode_encoder.rs +0 -0
  55. {ambers-0.4.2 → ambers-0.4.5}/src/compression/mod.rs +0 -0
  56. {ambers-0.4.2 → ambers-0.4.5}/src/constants.rs +0 -0
  57. {ambers-0.4.2 → ambers-0.4.5}/src/encoding.rs +0 -0
  58. {ambers-0.4.2 → ambers-0.4.5}/src/header.rs +0 -0
  59. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/encoding_record.rs +0 -0
  60. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/float_info.rs +0 -0
  61. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/integer_info.rs +0 -0
  62. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/long_var_names.rs +0 -0
  63. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/mod.rs +0 -0
  64. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/mr_sets.rs +0 -0
  65. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/var_attributes.rs +0 -0
  66. {ambers-0.4.2 → ambers-0.4.5}/src/info_records/very_long_strings.rs +0 -0
  67. {ambers-0.4.2 → ambers-0.4.5}/src/python/conversions.rs +0 -0
  68. {ambers-0.4.2 → ambers-0.4.5}/src/python/diff.rs +0 -0
  69. {ambers-0.4.2 → ambers-0.4.5}/src/python/mod.rs +0 -0
  70. {ambers-0.4.2 → ambers-0.4.5}/src/writer/data.rs +0 -0
  71. {ambers-0.4.2 → ambers-0.4.5}/src/writer/layout.rs +0 -0
  72. {ambers-0.4.2 → ambers-0.4.5}/src/writer/mod.rs +0 -0
  73. {ambers-0.4.2 → ambers-0.4.5}/src/writer/records.rs +0 -0
  74. {ambers-0.4.2 → ambers-0.4.5}/src/writer/tests.rs +0 -0
  75. {ambers-0.4.2 → ambers-0.4.5}/tests/bench_read.py +0 -0
  76. {ambers-0.4.2 → ambers-0.4.5}/tests/bench_write.py +0 -0
  77. {ambers-0.4.2 → ambers-0.4.5}/tests/conftest.py +0 -0
  78. {ambers-0.4.2 → ambers-0.4.5}/tests/diag_zsav.py +0 -0
  79. {ambers-0.4.2 → ambers-0.4.5}/tests/test_apply_labels.py +0 -0
  80. {ambers-0.4.2 → ambers-0.4.5}/tests/test_apply_missing.py +0 -0
  81. {ambers-0.4.2 → ambers-0.4.5}/tests/test_long_strings.py +0 -0
  82. {ambers-0.4.2 → ambers-0.4.5}/tests/test_medium_write.rs +0 -0
  83. {ambers-0.4.2 → ambers-0.4.5}/tests/test_metadata.py +0 -0
  84. {ambers-0.4.2 → ambers-0.4.5}/tests/test_metadata_api.py +0 -0
  85. {ambers-0.4.2 → ambers-0.4.5}/tests/test_paths.example.py +0 -0
  86. {ambers-0.4.2 → ambers-0.4.5}/tests/test_temporal.rs +0 -0
  87. {ambers-0.4.2 → ambers-0.4.5}/tests/test_validate.py +0 -0
  88. {ambers-0.4.2 → ambers-0.4.5}/tests/test_wide_columns.py +0 -0
  89. {ambers-0.4.2 → ambers-0.4.5}/tests/test_write_roundtrip.py +0 -0
  90. {ambers-0.4.2 → ambers-0.4.5}/validate.md +0 -0
@@ -60,4 +60,4 @@ jobs:
60
60
  - name: Run Python tests (small/synthetic data only)
61
61
  run: |
62
62
  uv pip install --system pytest
63
- pytest tests/test_apply_labels.py tests/test_apply_missing.py tests/test_validate.py tests/test_metadata_api.py tests/test_writer_issues.py -v -k "not RealFile"
63
+ pytest tests/test_apply_labels.py tests/test_apply_missing.py tests/test_validate.py tests/test_metadata_api.py tests/test_writer_issues.py tests/test_polars_compat.py tests/test_malformed.py tests/test_warnings.py -v -k "not RealFile"
@@ -1,6 +1,7 @@
1
1
  /target
2
2
  __pycache__/
3
3
  *.pyd
4
+ *.pdb
4
5
  *.so
5
6
  *.egg-info/
6
7
  dist/
@@ -2,6 +2,38 @@
2
2
 
3
3
  All notable changes to ambers are documented in this file.
4
4
 
5
+ ## [0.4.5] - 2026-10-07
6
+
7
+ - Add `warnings_and_errors.md`, a catalogue of every reader warning finding and error message with meaning and remedy, and a "Warnings and Errors" section at the end of the README
8
+
9
+ - Fix GitHub issue #4: a variable record whose type field is not 0, 1-255 or -1 is rejected (`InvalidVariable`); a garbage width of hundreds of millions made every row walk millions of string segments (seconds for a 4 KB file, now milliseconds). Negative values other than -1 are tolerated as continuation slots with a finding, since SPSS opens such files
10
+ - Fix GitHub issue #3: sizes declared by the file are checked before allocating. `read_bytes` refuses requests larger than the file, a variable may declare at most 3 missing values, buffer capacities are capped by the bytes actually present, and cold reservations are capped. Fuzzer files that requested 1-7 GB now fail or read in milliseconds without touching memory
11
+ - Date/time values outside years 1-9999 (or non-finite) are set to null and reported as a finding instead of being stored as saturated values that made Polars panic on display
12
+ - **Behaviour change (issue #1 follow-up):** a header row width that disagrees with the variable list is now a finding instead of an error, matching SPSS which ignores that field; the variable list is used. Duplicate variable names are now rejected with `InvalidDictionary` (SPSS rejects them too)
13
+ - Very-long-string declarations with an impossible width or more segments than variables remain are ignored with a finding
14
+ - Add file-damage warnings: when a file's header disagrees with its contents (declared row count vs rows read, compression bias other than 100, missing row width), `read_sav`/`scan_sav`/`read_sav_meta` emit `ambers.CorruptFileWarning` and list the findings in `SavFile.warnings` and `SpssMetadata.warnings` (also in `meta.schema["warnings"]` and `meta.summary()`). The data is still read exactly as stored, never silently corrected. Rust: new `SpssMetadata::warnings`; `read_sav` now returns metadata cloned after the read so it carries data-time findings
15
+ - Fix GitHub issue #2: a header declaring 0 cases while data follows made the reader write past a zero-length row buffer in release builds (process crash). The header case count is now only a capacity hint floored at one row, and the bounds check guarding the decompressor's unsafe writes is unconditional (`SpssError::Internal`) instead of debug-only. Such files now read the rows actually present, matching SPSS (the reporter's file: 5 rows). Legitimately empty files no longer trip a debug assertion. No change for files with a positive case count
16
+ - Fix GitHub issue #1: row width is now derived from the dictionary's type 2 records instead of the header's `nominal_case_size`. A file whose header disagrees with its dictionary is rejected with `invalid dictionary: header declares N slots per case but the dictionary defines M` (SPSS and pyreadstat reject such files too). Previously the mismatch caused an out-of-bounds read and returned garbage columns. A header value of 0 or -1 is tolerated, as some writers store that. No change for valid files (verified byte-identical output on all local test files)
17
+ - Add `SpssError::InvalidDictionary`
18
+ - Add `tests/test_malformed.rs` and `tests/test_malformed.py` (synthetic header/dictionary mismatch fixtures); Python test added to CI
19
+
20
+ ## [0.4.4] - 2026-09-18
21
+
22
+ - Fix `FutureWarning: from_arrow(<ArrowStreamExportable>) will return a Series` emitted by `read_sav()` and `scan_sav()` on Polars >= 1.44 — Arrow streams are now converted with `pl.DataFrame()` (available since Polars 1.3, which remains the minimum)
23
+ - Polars 2.0 compatibility: `read_sav()`/`scan_sav()` no longer break when `pl.from_arrow()` returns a Series; `codebook()` type detection casts before `is_in()` to satisfy 2.0's strict coercion. Full Python test suite passes on Polars 1.40, 1.44.2 and 2.0.0rc1
24
+ - Add `tests/test_polars_compat.py` (eager, lazy, and multi-batch conversion with FutureWarning treated as error); added to CI
25
+
26
+ ## [0.4.3] - 2026-04-30
27
+
28
+ - Add `codebook(df, meta)` — generate a Polars DataFrame data dictionary documenting every variable and its values
29
+ - Two views: `view="variables"` (default, one row per variable) and `view="values"` (one row per value)
30
+ - 5-way variable type detection: single-select, multi-select, numeric, text, date — with full multi-select tiers (MR sets, binary patterns, sibling series, generic binary)
31
+ - `values_format=` controls the variables-view `values` column: `"string"` (default, newline-joined `"1=Low\n2=Medium"`) for clean marimo HTML and Excel rendering; `"struct"` for `List[Struct{value_code, value_label}]` with `.explode().unnest()` workflows
32
+ - `include_meta=True` adds `variable_measure` and `variable_format` columns to the values view
33
+ - `columns=` and `exclude=` filtering combinable
34
+ - Strict validation: rejects unknown `view` values; rejects `values_format` with `view="values"`
35
+ - 40 tests; integration verified on real SPSS files
36
+
5
37
  ## [0.4.2] - 2026-04-07
6
38
 
7
39
  - Add `validate(df, meta)` — check value label quality: unlabeled values (error) and duplicate labels (warning)
@@ -33,7 +33,7 @@ dependencies = [
33
33
 
34
34
  [[package]]
35
35
  name = "ambers"
36
- version = "0.4.2"
36
+ version = "0.4.5"
37
37
  dependencies = [
38
38
  "arrow",
39
39
  "encoding_rs",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ambers"
3
- version = "0.4.2"
3
+ version = "0.4.5"
4
4
  edition = "2024"
5
5
  license = "MIT"
6
6
  description = "Pure Rust reader for SPSS .sav and .zsav files"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ambers
3
- Version: 0.4.2
3
+ Version: 0.4.5
4
4
  Requires-Dist: polars>=1.3
5
5
  License-File: LICENSE
6
6
  Summary: Pure Rust SPSS .sav/.zsav reader with Polars DataFrame output
@@ -125,9 +125,19 @@ report.to_frame() # DataFrame for
125
125
  | `sav.file_size` | `int \| None` | File size in bytes |
126
126
  | `sav.read_time` | `float \| None` | Wall-clock read time in seconds |
127
127
  | `sav.compression` | `str` | `"uncompressed"`, `"bytecode"`, or `"zlib"` |
128
+ | `sav.warnings` | `list[str]` | File-damage findings; empty for a healthy file |
128
129
 
129
130
  For `scan_sav()`, `read_time` measures metadata/schema reading only (not lazy collection).
130
131
 
132
+ **Damaged files.** ambers reads a file exactly as stored and never silently "corrects" values.
133
+ If the header disagrees with the contents (declared row count or row width vs what the file
134
+ holds, a non-standard compression bias, date/time values outside years 1-9999 which become
135
+ null), it raises a `CorruptFileWarning` naming the findings and lists them in
136
+ `sav.warnings` / `meta.warnings`. Treat such a file with suspicion and re-export it from the
137
+ source. Structures that cannot be read at all (duplicate variable names, an impossible
138
+ variable type, a record larger than the file) raise an `OSError` immediately. Silence the
139
+ warning with `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`.
140
+
131
141
  ### apply_labels
132
142
 
133
143
  Replace numeric/string codes with their SPSS value labels. By default produces Polars `Enum` columns that preserve SPSS definition order — crucial for Likert scales and survey analysis.
@@ -227,6 +237,7 @@ All fields returned by the reader. Fields marked **Write** are preserved when pa
227
237
  | `number_rows` | yes | — | `int \| None` |
228
238
  | `weight_variable` | yes | yes | `str \| None` |
229
239
  | `notes` | yes | yes | `list[str]` |
240
+ | `warnings` | yes | — | `list[str]` |
230
241
  | `variable_names` | yes | — | `list[str]` |
231
242
  | `variable_labels` | yes | yes | `dict[str, str]` |
232
243
  | `variable_value_labels` | yes | yes | `dict[str, dict[float\|str, str]]` |
@@ -356,6 +367,28 @@ On the 5.4 GB file, selecting 5 columns and 1000 rows completes in **13ms** —
356
367
  - Continued I/O performance optimization
357
368
  - Currently Polars-only — pandas/other DataFrame libraries may be added later
358
369
 
370
+ ## Warnings and Errors
371
+
372
+ ambers never silently "corrects" a damaged file. It either reads the data and tells you what
373
+ was wrong, or stops when the file cannot be read at all.
374
+
375
+ - **Warning, data returned** — the file contradicts itself but a more reliable part of it says
376
+ what the bytes mean. You get a `CorruptFileWarning` listing the findings, also available as
377
+ `sav.warnings` / `meta.warnings`. Examples: header row count or row width that disagrees with
378
+ the file, a non-standard compression bias (values may be shifted; SPSS assumes 100),
379
+ date/time values outside years 1-9999 (set to null), impossible very-long-string
380
+ declarations (ignored).
381
+ - **Error, nothing returned** — the structure needed to navigate the file is broken and no
382
+ guess would be safe. You get an `OSError` naming the cause. Examples: duplicate variable
383
+ names, an impossible variable type, a record larger than the file, a truncated file, a file
384
+ that is not SPSS at all.
385
+ - **Silence or escalate** — `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`
386
+ hides the warning (findings stay in `sav.warnings`); `warnings.simplefilter("error",
387
+ ambers.CorruptFileWarning)` makes any damaged file fatal in a pipeline.
388
+
389
+ See [warnings_and_errors.md](warnings_and_errors.md) for every message, what it means, what
390
+ ambers did, and what to do.
391
+
359
392
  ## License
360
393
 
361
394
  [MIT](LICENSE)
@@ -115,9 +115,19 @@ report.to_frame() # DataFrame for
115
115
  | `sav.file_size` | `int \| None` | File size in bytes |
116
116
  | `sav.read_time` | `float \| None` | Wall-clock read time in seconds |
117
117
  | `sav.compression` | `str` | `"uncompressed"`, `"bytecode"`, or `"zlib"` |
118
+ | `sav.warnings` | `list[str]` | File-damage findings; empty for a healthy file |
118
119
 
119
120
  For `scan_sav()`, `read_time` measures metadata/schema reading only (not lazy collection).
120
121
 
122
+ **Damaged files.** ambers reads a file exactly as stored and never silently "corrects" values.
123
+ If the header disagrees with the contents (declared row count or row width vs what the file
124
+ holds, a non-standard compression bias, date/time values outside years 1-9999 which become
125
+ null), it raises a `CorruptFileWarning` naming the findings and lists them in
126
+ `sav.warnings` / `meta.warnings`. Treat such a file with suspicion and re-export it from the
127
+ source. Structures that cannot be read at all (duplicate variable names, an impossible
128
+ variable type, a record larger than the file) raise an `OSError` immediately. Silence the
129
+ warning with `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`.
130
+
121
131
  ### apply_labels
122
132
 
123
133
  Replace numeric/string codes with their SPSS value labels. By default produces Polars `Enum` columns that preserve SPSS definition order — crucial for Likert scales and survey analysis.
@@ -217,6 +227,7 @@ All fields returned by the reader. Fields marked **Write** are preserved when pa
217
227
  | `number_rows` | yes | — | `int \| None` |
218
228
  | `weight_variable` | yes | yes | `str \| None` |
219
229
  | `notes` | yes | yes | `list[str]` |
230
+ | `warnings` | yes | — | `list[str]` |
220
231
  | `variable_names` | yes | — | `list[str]` |
221
232
  | `variable_labels` | yes | yes | `dict[str, str]` |
222
233
  | `variable_value_labels` | yes | yes | `dict[str, dict[float\|str, str]]` |
@@ -346,6 +357,28 @@ On the 5.4 GB file, selecting 5 columns and 1000 rows completes in **13ms** —
346
357
  - Continued I/O performance optimization
347
358
  - Currently Polars-only — pandas/other DataFrame libraries may be added later
348
359
 
360
+ ## Warnings and Errors
361
+
362
+ ambers never silently "corrects" a damaged file. It either reads the data and tells you what
363
+ was wrong, or stops when the file cannot be read at all.
364
+
365
+ - **Warning, data returned** — the file contradicts itself but a more reliable part of it says
366
+ what the bytes mean. You get a `CorruptFileWarning` listing the findings, also available as
367
+ `sav.warnings` / `meta.warnings`. Examples: header row count or row width that disagrees with
368
+ the file, a non-standard compression bias (values may be shifted; SPSS assumes 100),
369
+ date/time values outside years 1-9999 (set to null), impossible very-long-string
370
+ declarations (ignored).
371
+ - **Error, nothing returned** — the structure needed to navigate the file is broken and no
372
+ guess would be safe. You get an `OSError` naming the cause. Examples: duplicate variable
373
+ names, an impossible variable type, a record larger than the file, a truncated file, a file
374
+ that is not SPSS at all.
375
+ - **Silence or escalate** — `warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)`
376
+ hides the warning (findings stay in `sav.warnings`); `warnings.simplefilter("error",
377
+ ambers.CorruptFileWarning)` makes any damaged file fatal in a pipeline.
378
+
379
+ See [warnings_and_errors.md](warnings_and_errors.md) for every message, what it means, what
380
+ ambers did, and what to do.
381
+
349
382
  ## License
350
383
 
351
384
  [MIT](LICENSE)
@@ -4,7 +4,7 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "ambers"
7
- version = "0.4.2"
7
+ version = "0.4.5"
8
8
  description = "Pure Rust SPSS .sav/.zsav reader with Polars DataFrame output"
9
9
  license = { text = "MIT" }
10
10
  readme = "README.md"
@@ -6,11 +6,14 @@ from ambers._io import read_sav, read_sav_meta, scan_sav, write_sav
6
6
  from ambers._missing import apply_missing
7
7
  from ambers._transforms import apply_labels
8
8
  from ambers._validate import ValidationIssue, ValidationReport, validate
9
+ from ambers._warnings import CorruptFileWarning
10
+ from ambers.codebook import codebook
9
11
 
10
12
  __all__ = [
11
13
  "SavFile",
12
14
  "apply_labels",
13
15
  "apply_missing",
16
+ "codebook",
14
17
  "validate",
15
18
  "ValidationReport",
16
19
  "ValidationIssue",
@@ -20,4 +23,5 @@ __all__ = [
20
23
  "write_sav",
21
24
  "SpssMetadata",
22
25
  "MetaDiff",
26
+ "CorruptFileWarning",
23
27
  ]
@@ -8,6 +8,15 @@ import polars
8
8
 
9
9
  T = TypeVar("T", polars.DataFrame, polars.LazyFrame)
10
10
 
11
+ class CorruptFileWarning(UserWarning):
12
+ """The .sav file appears damaged or corrupted: its header disagrees with its contents.
13
+
14
+ Emitted by ``read_sav``, ``scan_sav`` and ``read_sav_meta``. The data is read exactly as
15
+ stored; the findings are listed in ``SavFile.warnings`` / ``SpssMetadata.warnings``.
16
+ Silence with ``warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)``.
17
+ """
18
+ ...
19
+
11
20
  @dataclass
12
21
  class SavFile(Generic[T]):
13
22
  """Result of reading an SPSS .sav/.zsav file.
@@ -27,6 +36,8 @@ class SavFile(Generic[T]):
27
36
  read_time
28
37
  Wall-clock seconds for the read operation, or None if not measured.
29
38
  For ``scan_sav`` this covers metadata/schema reading only.
39
+ warnings
40
+ File-damage findings (empty for a healthy file); see ``CorruptFileWarning``.
30
41
 
31
42
  Examples
32
43
  --------
@@ -43,6 +54,7 @@ class SavFile(Generic[T]):
43
54
  shape: tuple[int, int] | None = ...
44
55
  file_size: int | None = ...
45
56
  read_time: float | None = ...
57
+ warnings: list[str] = ...
46
58
 
47
59
  @property
48
60
  def compression(self) -> str:
@@ -336,6 +348,15 @@ class SpssMetadata:
336
348
  """Document record notes (list of strings)."""
337
349
  ...
338
350
  @property
351
+ def warnings(self) -> list[str]:
352
+ """File-damage findings recorded while reading (empty for a healthy file).
353
+
354
+ Each entry describes a way the header disagrees with the file contents, e.g.
355
+ ``"header declares 0 rows but 5 rows were read"`` or a non-standard compression
356
+ bias. Read-only; never written back to a file.
357
+ """
358
+ ...
359
+ @property
339
360
  def number_rows(self) -> int | None:
340
361
  """Row count from the file header, or None if not recorded."""
341
362
  ...
@@ -405,10 +426,10 @@ class SpssMetadata:
405
426
  ...
406
427
  @property
407
428
  def schema(self) -> dict:
408
- """Full metadata as a nested Python dict (22 fields).
429
+ """Full metadata as a nested Python dict (23 fields).
409
430
 
410
431
  Field order: file_label, file_format, file_encoding, creation_time,
411
- compression, number_columns, number_rows, weight_variable, notes,
432
+ compression, number_columns, number_rows, weight_variable, notes, warnings,
412
433
  variable_names, variable_labels, variable_value_labels,
413
434
  variable_formats, variable_measures, variable_alignments,
414
435
  variable_storage_widths, variable_display_widths, variable_roles,
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import os
6
- from dataclasses import dataclass
6
+ from dataclasses import dataclass, field
7
7
  from typing import Generic, TypeVar
8
8
 
9
9
  import polars as pl
@@ -37,6 +37,10 @@ class SavFile(Generic[T]):
37
37
  read_time: Wall-clock seconds for the read operation, or None if
38
38
  not measured. For ``scan_sav`` this covers metadata/schema
39
39
  reading only (not lazy collection).
40
+ warnings: File-damage findings (empty for a healthy file). Each entry
41
+ describes a way the file's header disagrees with its contents.
42
+ A ``CorruptFileWarning`` was emitted when this is non-empty. The
43
+ data is always read exactly as stored.
40
44
  """
41
45
 
42
46
  data: T
@@ -45,6 +49,7 @@ class SavFile(Generic[T]):
45
49
  shape: tuple[int, int] | None = None
46
50
  file_size: int | None = None
47
51
  read_time: float | None = None
52
+ warnings: list[str] = field(default_factory=list)
48
53
 
49
54
  @property
50
55
  def compression(self) -> str:
@@ -78,6 +83,11 @@ class SavFile(Generic[T]):
78
83
  if not isinstance(self.data, pl.DataFrame):
79
84
  time_str += " (metadata only)"
80
85
  lines.append(("Read time", time_str))
86
+ # Warnings line (only when the file looks damaged)
87
+ if self.warnings:
88
+ n = len(self.warnings)
89
+ noun = "finding" if n == 1 else "findings"
90
+ lines.append(("Warnings", f"{n} {noun} - file may be damaged, see .warnings"))
81
91
  # Build box
82
92
  label_w = max(len(label) for label, _ in lines)
83
93
  content_parts = [f"{label:<{label_w}} {value}" for label, value in lines]
@@ -17,6 +17,7 @@ from ambers._ambers import (
17
17
  )
18
18
 
19
19
  from ambers._containers import SavFile, _get_dtype_map, _resolve_columns
20
+ from ambers._warnings import warn_if_damaged
20
21
 
21
22
 
22
23
  def read_sav(
@@ -65,16 +66,18 @@ def read_sav(
65
66
  resolved = None
66
67
 
67
68
  stream, meta = _read_sav(str(path), columns=resolved, n_rows=n_rows)
68
- df = pl.from_arrow(stream)
69
+ df = pl.DataFrame(stream)
69
70
  if row_index_name is not None:
70
71
  df = df.with_row_index(row_index_name, offset=row_index_offset)
71
72
 
72
73
  read_time = time.perf_counter() - t0
74
+ file_warnings = warn_if_damaged(meta, path)
73
75
 
74
76
  return SavFile(
75
77
  data=df, meta=meta, source=str(path),
76
78
  shape=(df.height, df.width),
77
79
  file_size=file_size, read_time=read_time,
80
+ warnings=file_warnings,
78
81
  )
79
82
 
80
83
 
@@ -95,7 +98,9 @@ def read_sav_meta(path: str) -> SpssMetadata:
95
98
  >>> meta.variable_names
96
99
  >>> meta.label("Q1")
97
100
  """
98
- return _read_sav_meta(str(path))
101
+ meta = _read_sav_meta(str(path))
102
+ warn_if_damaged(meta, path)
103
+ return meta
99
104
 
100
105
 
101
106
  def scan_sav(
@@ -149,6 +154,8 @@ def scan_sav(
149
154
  reader = _SavBatchReader(str(path))
150
155
  meta = reader.metadata()
151
156
  raw_schema = reader.schema()
157
+ # Header-level findings only: the row count is not known until collected.
158
+ file_warnings = warn_if_damaged(meta, path)
152
159
 
153
160
  # Resolve int indices to column names
154
161
  resolved = _resolve_columns(columns, meta.variable_names)
@@ -186,7 +193,7 @@ def scan_sav(
186
193
  scanner.limit(min(limits))
187
194
 
188
195
  while (batch := scanner.next_batch()) is not None:
189
- df = pl.from_arrow(batch)
196
+ df = pl.DataFrame(batch)
190
197
  if predicate is not None:
191
198
  df = df.filter(predicate)
192
199
  yield df
@@ -198,6 +205,7 @@ def scan_sav(
198
205
  return SavFile(
199
206
  data=lf, meta=meta, source=str(path),
200
207
  shape=shape, file_size=file_size, read_time=read_time,
208
+ warnings=file_warnings,
201
209
  )
202
210
 
203
211
 
@@ -0,0 +1,44 @@
1
+ """File-damage warnings: tell the caller when a .sav file looks corrupted.
2
+
3
+ ambers always reads a file exactly as stored and never "corrects" values to
4
+ what SPSS would assume. When the file's header disagrees with its contents
5
+ (row count, compression bias, row width), the Rust reader records a message in
6
+ ``SpssMetadata.warnings``; this module turns those into one Python warning so
7
+ notebooks and scripts see it immediately, and returns the list for
8
+ ``SavFile.warnings``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import warnings
15
+
16
+ from ambers._ambers import SpssMetadata
17
+
18
+
19
+ class CorruptFileWarning(UserWarning):
20
+ """The .sav file appears damaged or corrupted.
21
+
22
+ Its header disagrees with its contents, so the values may not be what the
23
+ file's author stored. The data was read exactly as found in the file.
24
+ Silence with ``warnings.filterwarnings("ignore", category=ambers.CorruptFileWarning)``.
25
+ """
26
+
27
+
28
+ def warn_if_damaged(meta: SpssMetadata, source: str | os.PathLike | None, *, stacklevel: int = 3) -> list[str]:
29
+ """Emit one ``CorruptFileWarning`` summarising ``meta.warnings`` and return them.
30
+
31
+ ``stacklevel=3`` points the warning at the caller of the public ambers
32
+ function (``warn_if_damaged`` -> ``read_sav`` -> user code).
33
+ """
34
+ found = list(meta.warnings)
35
+ if found:
36
+ name = os.path.basename(str(source)) if source else "SPSS file"
37
+ details = "; ".join(f"({i}) {m}" for i, m in enumerate(found, 1))
38
+ warnings.warn(
39
+ f"{name} appears damaged or corrupted; please double-check the source. "
40
+ f"Findings: {details}. The data was read exactly as stored in the file.",
41
+ CorruptFileWarning,
42
+ stacklevel=stacklevel,
43
+ )
44
+ return found