de-censor 0.7.0__tar.gz → 0.7.1__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 (69) hide show
  1. de_censor-0.7.1/PKG-INFO +99 -0
  2. de_censor-0.7.1/README.md +74 -0
  3. {de_censor-0.7.0 → de_censor-0.7.1}/pyproject.toml +1 -1
  4. de_censor-0.7.1/src/censor/audit.py +117 -0
  5. de_censor-0.7.1/src/censor/checks/__init__.py +50 -0
  6. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/checks/agent.py +2 -9
  7. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/checks/correctness.py +14 -23
  8. de_censor-0.7.1/src/censor/checks/data_health.py +145 -0
  9. de_censor-0.7.1/src/censor/checks/freshness.py +135 -0
  10. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/checks/guards.py +3 -9
  11. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/checks/operability.py +6 -11
  12. de_censor-0.7.1/src/censor/checks/reliability.py +187 -0
  13. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/checks/security.py +7 -17
  14. de_censor-0.7.1/src/censor/checks/staleness.py +82 -0
  15. de_censor-0.7.1/src/censor/cli.py +259 -0
  16. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/context.py +9 -1
  17. de_censor-0.7.1/src/censor/data.py +279 -0
  18. de_censor-0.7.1/src/censor/derive.py +86 -0
  19. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/history.py +46 -13
  20. de_censor-0.7.1/src/censor/limits.py +81 -0
  21. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/model.py +10 -2
  22. de_censor-0.7.1/src/censor/postgres.py +175 -0
  23. de_censor-0.7.1/src/censor/reading.py +32 -0
  24. de_censor-0.7.1/src/censor/readings.py +107 -0
  25. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/report.py +19 -0
  26. de_censor-0.7.1/src/censor/result.py +28 -0
  27. de_censor-0.7.1/src/censor/runner.py +53 -0
  28. de_censor-0.7.1/src/censor/state.py +193 -0
  29. de_censor-0.7.1/src/censor/target.py +86 -0
  30. de_censor-0.7.1/tests/_data.py +36 -0
  31. de_censor-0.7.1/tests/_state.py +90 -0
  32. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_cli.py +14 -5
  33. de_censor-0.7.1/tests/test_cli_standard.py +162 -0
  34. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_context.py +10 -0
  35. de_censor-0.7.1/tests/test_data_health.py +278 -0
  36. de_censor-0.7.1/tests/test_derive.py +92 -0
  37. de_censor-0.7.1/tests/test_freshness.py +120 -0
  38. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_history.py +20 -0
  39. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_operability.py +15 -0
  40. de_censor-0.7.1/tests/test_postgres_target.py +196 -0
  41. de_censor-0.7.1/tests/test_postgres_unit.py +42 -0
  42. de_censor-0.7.1/tests/test_read_only.py +83 -0
  43. de_censor-0.7.1/tests/test_reliability.py +91 -0
  44. de_censor-0.7.1/tests/test_staleness.py +120 -0
  45. de_censor-0.7.1/tests/test_state.py +147 -0
  46. de_censor-0.7.1/tests/test_target_runner.py +76 -0
  47. de_censor-0.7.0/PKG-INFO +0 -39
  48. de_censor-0.7.0/README.md +0 -14
  49. de_censor-0.7.0/src/censor/audit.py +0 -36
  50. de_censor-0.7.0/src/censor/checks/__init__.py +0 -17
  51. de_censor-0.7.0/src/censor/cli.py +0 -109
  52. de_censor-0.7.0/src/censor/runner.py +0 -38
  53. {de_censor-0.7.0 → de_censor-0.7.1}/.gitignore +0 -0
  54. {de_censor-0.7.0 → de_censor-0.7.1}/LICENSE +0 -0
  55. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/__init__.py +0 -0
  56. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/grade.py +0 -0
  57. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/py.typed +0 -0
  58. {de_censor-0.7.0 → de_censor-0.7.1}/src/censor/scoring.py +0 -0
  59. {de_censor-0.7.0 → de_censor-0.7.1}/tests/_projects.py +0 -0
  60. {de_censor-0.7.0 → de_censor-0.7.1}/tests/conftest.py +0 -0
  61. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_agent.py +0 -0
  62. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_audit_maturity.py +0 -0
  63. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_correctness.py +0 -0
  64. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_guards.py +0 -0
  65. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_import.py +0 -0
  66. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_model_grade_scoring.py +0 -0
  67. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_report.py +0 -0
  68. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_runner.py +0 -0
  69. {de_censor-0.7.0 → de_censor-0.7.1}/tests/test_security.py +0 -0
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.5
2
+ Name: de-censor
3
+ Version: 0.7.1
4
+ Summary: Censor — audit a DE Arsenal project or dataset and grade it, with evidence and fixes
5
+ Project-URL: Homepage, https://github.com/KooEric/de-arsenal
6
+ Project-URL: Repository, https://github.com/KooEric/de-arsenal
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Database
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: arsenal-core<0.8,>=0.7
18
+ Requires-Dist: de-arsenal<0.8,>=0.7
19
+ Requires-Dist: de-gladius<0.8,>=0.7
20
+ Requires-Dist: pyarrow>=17
21
+ Requires-Dist: pydantic>=2
22
+ Requires-Dist: pyyaml>=6
23
+ Requires-Dist: typer>=0.12
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Censor (`de-censor`)
27
+
28
+ > 감찰관. 파이프라인과 데이터셋을 조사해 등급을 매기고, 고칠 곳을 근거와 함께 남긴다.
29
+
30
+ ```bash
31
+ censor audit . # grade the project in the current directory (quick tier)
32
+ censor audit . --tier standard # also read run state and the data the project wrote
33
+ censor report # grade history
34
+ censor compare <run_a> <run_b> # checks whose status changed
35
+ arsenal eval . # same as `censor audit .`
36
+ ```
37
+
38
+ Results go to stdout as JSON (`schemas/censor-report.json`), a summary to stderr, and history
39
+ and a Markdown report to `.arsenal/censor/`. Exit code 0 means no failed check, 1 means at
40
+ least one, 2 means Censor could not run or could not read the target.
41
+
42
+ Censor only reads. It never runs a pipeline and never writes to what it audits: the one place
43
+ it writes is `.arsenal/censor/` (run state is read from a copy made there, DuckDB files are
44
+ attached read-only, Postgres is attached `READ_ONLY`).
45
+
46
+ ## Tiers
47
+
48
+ | Tier | Reads | Dimensions |
49
+ |---|---|---|
50
+ | `quick` | project files and their times | correctness, quality guards, security, operability, agent readiness |
51
+ | `standard` | also run state and data | the five above, plus reliability, freshness, data health |
52
+
53
+ - **Operability** includes a file-time check on every tier: when a pipeline's newest output (or,
54
+ for a remote sink, its state file) is older than `--max-age-hours`, or a week when none is
55
+ given, it warns. No data is opened, so a stopped pipeline no longer grades like a running one.
56
+ - **Reliability**: failed or quarantined units, the share of rows validation set aside (DLQ),
57
+ whether output is still there after a failure. A pipeline that never ran is not scored.
58
+ - **Freshness**: the last completed unit, the `arsenal dataset` publication state, and whether
59
+ any limit says when data is too old (`--max-age-hours`, or `arsenal dataset --max-age-hours`).
60
+ With no limit, a last success older than a week warns instead of passing.
61
+ - **Data health**: row count, key uniqueness and NULLs, NULL ratio per column (warn from 50%,
62
+ fail when a column is entirely NULL), and the period a time column covers. For a project the
63
+ data is found from the specs: Parquet and DuckDB sinks, and transform outputs.
64
+
65
+ ## Auditing a dataset without a project
66
+
67
+ ```bash
68
+ censor audit --files 'data/*.parquet' --key id --time-column created_at
69
+ censor audit --duckdb .arsenal/dataset.duckdb --table published --key id
70
+ censor audit --table public.orders --postgres-dsn-env PG_DSN --key id --max-age-hours 24
71
+ ```
72
+
73
+ A dataset gets data health and freshness only; history goes to `.arsenal/censor/` in the
74
+ current directory (or in `DIR` when one is given). The Postgres DSN is read from the named
75
+ environment variable and is never printed. `--files` takes Parquet, CSV/TSV or JSON lines.
76
+
77
+ ## Large data
78
+
79
+ Before reading, Censor measures: file count and size, DuckDB's row estimate, or Postgres
80
+ catalog statistics. Over 2,000 files, 5 GB or 50 million estimated rows (and for views, whose
81
+ size is unknown) the data-health checks are skipped and the report says how to narrow the read:
82
+
83
+ | Option | Effect |
84
+ |---|---|
85
+ | `--sample 1%` | profile a sample. A duplicate found in it fails; none found only warns |
86
+ | `--since 2026-11-01` | only rows from that date (needs `--time-column`) |
87
+ | `--full` | read everything |
88
+ | `--memory-limit 4GB` | DuckDB memory limit; more spills to `.arsenal/censor/tmp/` |
89
+ | `--timeout 120` | seconds per query; a query that runs out is `na`, not a failure |
90
+
91
+ Samples are repeatable. For files and DuckDB: by key hash when `--key` is given (so every row
92
+ of a sampled key is read), otherwise a seeded row sample. For a Postgres table:
93
+ `TABLESAMPLE SYSTEM` with a fixed seed, run on the server, whatever the key (a Postgres view
94
+ is sampled in DuckDB instead).
95
+
96
+ Auditing Postgres needs DuckDB's `postgres` extension. DuckDB downloads it once into its own
97
+ directory (`~/.duckdb/extensions`); that is the only thing written outside `.arsenal/censor/`.
98
+
99
+ Design: `docs/plans/2026-11-25-censor-design.md`.
@@ -0,0 +1,74 @@
1
+ # Censor (`de-censor`)
2
+
3
+ > 감찰관. 파이프라인과 데이터셋을 조사해 등급을 매기고, 고칠 곳을 근거와 함께 남긴다.
4
+
5
+ ```bash
6
+ censor audit . # grade the project in the current directory (quick tier)
7
+ censor audit . --tier standard # also read run state and the data the project wrote
8
+ censor report # grade history
9
+ censor compare <run_a> <run_b> # checks whose status changed
10
+ arsenal eval . # same as `censor audit .`
11
+ ```
12
+
13
+ Results go to stdout as JSON (`schemas/censor-report.json`), a summary to stderr, and history
14
+ and a Markdown report to `.arsenal/censor/`. Exit code 0 means no failed check, 1 means at
15
+ least one, 2 means Censor could not run or could not read the target.
16
+
17
+ Censor only reads. It never runs a pipeline and never writes to what it audits: the one place
18
+ it writes is `.arsenal/censor/` (run state is read from a copy made there, DuckDB files are
19
+ attached read-only, Postgres is attached `READ_ONLY`).
20
+
21
+ ## Tiers
22
+
23
+ | Tier | Reads | Dimensions |
24
+ |---|---|---|
25
+ | `quick` | project files and their times | correctness, quality guards, security, operability, agent readiness |
26
+ | `standard` | also run state and data | the five above, plus reliability, freshness, data health |
27
+
28
+ - **Operability** includes a file-time check on every tier: when a pipeline's newest output (or,
29
+ for a remote sink, its state file) is older than `--max-age-hours`, or a week when none is
30
+ given, it warns. No data is opened, so a stopped pipeline no longer grades like a running one.
31
+ - **Reliability**: failed or quarantined units, the share of rows validation set aside (DLQ),
32
+ whether output is still there after a failure. A pipeline that never ran is not scored.
33
+ - **Freshness**: the last completed unit, the `arsenal dataset` publication state, and whether
34
+ any limit says when data is too old (`--max-age-hours`, or `arsenal dataset --max-age-hours`).
35
+ With no limit, a last success older than a week warns instead of passing.
36
+ - **Data health**: row count, key uniqueness and NULLs, NULL ratio per column (warn from 50%,
37
+ fail when a column is entirely NULL), and the period a time column covers. For a project the
38
+ data is found from the specs: Parquet and DuckDB sinks, and transform outputs.
39
+
40
+ ## Auditing a dataset without a project
41
+
42
+ ```bash
43
+ censor audit --files 'data/*.parquet' --key id --time-column created_at
44
+ censor audit --duckdb .arsenal/dataset.duckdb --table published --key id
45
+ censor audit --table public.orders --postgres-dsn-env PG_DSN --key id --max-age-hours 24
46
+ ```
47
+
48
+ A dataset gets data health and freshness only; history goes to `.arsenal/censor/` in the
49
+ current directory (or in `DIR` when one is given). The Postgres DSN is read from the named
50
+ environment variable and is never printed. `--files` takes Parquet, CSV/TSV or JSON lines.
51
+
52
+ ## Large data
53
+
54
+ Before reading, Censor measures: file count and size, DuckDB's row estimate, or Postgres
55
+ catalog statistics. Over 2,000 files, 5 GB or 50 million estimated rows (and for views, whose
56
+ size is unknown) the data-health checks are skipped and the report says how to narrow the read:
57
+
58
+ | Option | Effect |
59
+ |---|---|
60
+ | `--sample 1%` | profile a sample. A duplicate found in it fails; none found only warns |
61
+ | `--since 2026-11-01` | only rows from that date (needs `--time-column`) |
62
+ | `--full` | read everything |
63
+ | `--memory-limit 4GB` | DuckDB memory limit; more spills to `.arsenal/censor/tmp/` |
64
+ | `--timeout 120` | seconds per query; a query that runs out is `na`, not a failure |
65
+
66
+ Samples are repeatable. For files and DuckDB: by key hash when `--key` is given (so every row
67
+ of a sampled key is read), otherwise a seeded row sample. For a Postgres table:
68
+ `TABLESAMPLE SYSTEM` with a fixed seed, run on the server, whatever the key (a Postgres view
69
+ is sampled in DuckDB instead).
70
+
71
+ Auditing Postgres needs DuckDB's `postgres` extension. DuckDB downloads it once into its own
72
+ directory (`~/.duckdb/extensions`); that is the only thing written outside `.arsenal/censor/`.
73
+
74
+ Design: `docs/plans/2026-11-25-censor-design.md`.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "de-censor"
3
- version = "0.7.0"
3
+ version = "0.7.1"
4
4
  description = "Censor — audit a DE Arsenal project or dataset and grade it, with evidence and fixes"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -0,0 +1,117 @@
1
+ """Load -> check -> score. The one entry point the CLI calls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field, replace
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+ from typing import Final
10
+
11
+ from arsenal_core.errors import FatalError
12
+ from censor import __version__
13
+ from censor.checks import QUICK_CHECKS, STANDARD_CHECKS
14
+ from censor.context import load_context
15
+ from censor.model import AuditReport
16
+ from censor.readings import read_targets
17
+ from censor.runner import run_checks
18
+ from censor.scoring import score_checks
19
+ from censor.target import AuditContext, DataTarget, ScanOptions, Tier, kind_of
20
+
21
+ _MEMORY_LIMIT: Final = re.compile(r"\d+(\.\d+)?\s*[KMGT]i?B", re.IGNORECASE)
22
+
23
+
24
+ def new_run_id(tier: str, now: datetime | None = None) -> str:
25
+ moment = (now or datetime.now(UTC)).astimezone(UTC)
26
+ return f"{moment:%Y%m%d-%H%M%S}-{tier}"
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class AuditRequest:
31
+ root: Path # project directory, or where a data target's history goes
32
+ tier: Tier = "quick"
33
+ now: datetime | None = None
34
+ data: DataTarget | None = None
35
+ key: tuple[str, ...] = ()
36
+ time_column: str | None = None
37
+ max_age_hours: float | None = None
38
+ scan: ScanOptions = field(default_factory=ScanOptions)
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class AuditOutcome:
43
+ report: AuditReport
44
+ tool_errors: tuple[str, ...] = () # the target could not be read: exit code 2
45
+
46
+
47
+ def _validate(request: AuditRequest) -> None:
48
+ scan = request.scan
49
+ if request.data is not None and request.tier == "quick":
50
+ raise FatalError(
51
+ "a data target needs --tier standard: the quick tier reads project files only"
52
+ )
53
+ if scan.sample_percent is not None and not 0 < scan.sample_percent <= 100:
54
+ raise FatalError("--sample must be above 0 and at most 100 (percent)")
55
+ if scan.since is not None and request.time_column is None:
56
+ raise FatalError("--since needs --time-column")
57
+ if not _MEMORY_LIMIT.fullmatch(scan.memory_limit.strip()):
58
+ raise FatalError(f"invalid --memory-limit {scan.memory_limit!r}: use a size such as 4GB")
59
+ if scan.timeout_seconds <= 0:
60
+ raise FatalError("--timeout must be above 0 seconds")
61
+ if request.max_age_hours is not None and request.max_age_hours < 0:
62
+ raise FatalError("--max-age-hours must not be negative")
63
+
64
+
65
+ def _context(request: AuditRequest, now: datetime) -> AuditContext:
66
+ root = request.root.absolute()
67
+ if request.data is None:
68
+ return AuditContext(
69
+ kind="project",
70
+ root=root,
71
+ now=now,
72
+ project=load_context(root),
73
+ max_age_hours=request.max_age_hours,
74
+ )
75
+ return AuditContext(
76
+ kind=kind_of(request.data),
77
+ root=root,
78
+ now=now,
79
+ data=request.data,
80
+ key=request.key,
81
+ time_column=request.time_column,
82
+ max_age_hours=request.max_age_hours,
83
+ scan=request.scan,
84
+ )
85
+
86
+
87
+ def run_audit(request: AuditRequest) -> AuditOutcome:
88
+ now = (request.now or datetime.now(UTC)).astimezone(UTC)
89
+ _validate(request)
90
+ ctx = _context(request, now)
91
+ groups = QUICK_CHECKS
92
+ if request.tier == "standard":
93
+ ctx = replace(ctx, readings=read_targets(ctx))
94
+ groups = STANDARD_CHECKS
95
+ checks = run_checks(ctx, groups)
96
+ scored = score_checks(checks)
97
+ report = AuditReport(
98
+ run_id=new_run_id(request.tier, now),
99
+ tier=request.tier,
100
+ target=str(ctx.root) if ctx.data is None else ctx.data.label,
101
+ target_kind=ctx.kind,
102
+ censor_version=__version__,
103
+ score=scored.score,
104
+ grade=scored.grade,
105
+ capped_by_blocker=scored.capped_by_blocker,
106
+ dimensions=scored.dimensions,
107
+ checks=checks,
108
+ sample=next((r.sample for r in ctx.readings if r.sample), None),
109
+ since=request.scan.since.isoformat() if request.scan.since else None,
110
+ notices=[r.notice for r in ctx.readings if r.notice],
111
+ )
112
+ return AuditOutcome(report, tuple(r.tool_error for r in ctx.readings if r.tool_error))
113
+
114
+
115
+ def audit_project(root: Path, *, now: datetime | None = None) -> AuditReport:
116
+ """Quick audit of a project (reads files only)."""
117
+ return run_audit(AuditRequest(root=root, tier="quick", now=now)).report
@@ -0,0 +1,50 @@
1
+ """Check groups by tier. Quick reads files only; Standard also reads state and data."""
2
+
3
+ from collections.abc import Callable
4
+
5
+ from censor.checks.agent import check_agent_readiness
6
+ from censor.checks.correctness import check_correctness
7
+ from censor.checks.data_health import check_data_health
8
+ from censor.checks.freshness import check_freshness
9
+ from censor.checks.guards import check_guards
10
+ from censor.checks.operability import check_operability
11
+ from censor.checks.reliability import check_reliability
12
+ from censor.checks.security import check_security
13
+ from censor.checks.staleness import check_staleness
14
+ from censor.context import ProjectContext
15
+ from censor.model import CheckResult, Dimension
16
+ from censor.runner import CheckGroup
17
+ from censor.target import PROJECT_ONLY, AuditContext
18
+
19
+ Group = CheckGroup[AuditContext]
20
+
21
+
22
+ def _project(
23
+ name: str, dimension: Dimension, fn: Callable[[ProjectContext], list[CheckResult]]
24
+ ) -> Group:
25
+ """A Quick group: reads the project's files, so it applies to project targets only."""
26
+
27
+ def run(ctx: AuditContext) -> list[CheckResult]:
28
+ if ctx.project is None:
29
+ raise RuntimeError(f"{name} needs a project target")
30
+ return fn(ctx.project)
31
+
32
+ return CheckGroup(name, dimension, run, kinds=PROJECT_ONLY)
33
+
34
+
35
+ QUICK_CHECKS: tuple[Group, ...] = (
36
+ _project("correctness", Dimension.CORRECTNESS, check_correctness),
37
+ _project("guards", Dimension.GUARDS, check_guards),
38
+ _project("security", Dimension.SECURITY, check_security),
39
+ _project("operability", Dimension.OPERABILITY, check_operability),
40
+ _project("agent", Dimension.AGENT_READINESS, check_agent_readiness),
41
+ # File times only: a stopped pipeline must not grade like a running one.
42
+ CheckGroup("staleness", Dimension.OPERABILITY, check_staleness, kinds=PROJECT_ONLY),
43
+ )
44
+
45
+ STANDARD_CHECKS: tuple[Group, ...] = (
46
+ *QUICK_CHECKS,
47
+ CheckGroup("reliability", Dimension.RELIABILITY, check_reliability, kinds=PROJECT_ONLY),
48
+ CheckGroup("freshness", Dimension.FRESHNESS, check_freshness),
49
+ CheckGroup("data_health", Dimension.DATA_HEALTH, check_data_health),
50
+ )
@@ -11,6 +11,7 @@ from typing import Any, Final, cast
11
11
 
12
12
  from censor.context import ProjectContext
13
13
  from censor.model import CheckResult, Dimension, Status
14
+ from censor.result import make_result
14
15
 
15
16
  PLUGIN_PREFIX: Final = "de-arsenal@"
16
17
  REQUIRED_COMMANDS: Final = ("arsenal check", "arsenal run")
@@ -20,15 +21,7 @@ _STATE_DIR: Final = ".arsenal"
20
21
  def _r(
21
22
  check_id: str, weight: int, status: Status, subject: str, evidence: str, fix: str
22
23
  ) -> CheckResult:
23
- return CheckResult(
24
- id=check_id,
25
- dimension=Dimension.AGENT_READINESS,
26
- weight=weight,
27
- status=status,
28
- subject=subject,
29
- evidence=evidence,
30
- fix=fix if status != Status.PASS else "",
31
- )
24
+ return make_result(check_id, Dimension.AGENT_READINESS, weight, status, subject, evidence, fix)
32
25
 
33
26
 
34
27
  def _settings(root: Path) -> tuple[dict[str, Any], str | None]:
@@ -8,30 +8,22 @@ from typing import Final
8
8
 
9
9
  from arsenal.project import DbtProjectRef
10
10
 
11
- from arsenal_core.errors import ArsenalError
11
+ from arsenal_core.errors import ArsenalError, MissingEnvError
12
12
  from arsenal_core.spec import load_pipeline
13
13
  from censor.context import ProjectContext
14
14
  from censor.model import CheckResult, Dimension, Status
15
+ from censor.result import make_result
15
16
  from gladius.compile import compile_sql
16
17
  from gladius.loader import load_transform
17
18
 
18
19
  _DIM: Final = Dimension.CORRECTNESS
19
- _ENV_NOT_SET: Final = "environment variable not set"
20
20
 
21
21
 
22
22
  def _result(
23
23
  check_id: str, weight: int, status: Status, subject: str, evidence: str, fix: str = ""
24
24
  ) -> CheckResult:
25
- return CheckResult(
26
- id=check_id,
27
- dimension=_DIM,
28
- weight=weight,
29
- status=status,
30
- blocker=status == Status.FAIL,
31
- subject=subject,
32
- evidence=evidence,
33
- fix=fix,
34
- )
25
+ blocker = status == Status.FAIL
26
+ return make_result(check_id, _DIM, weight, status, subject, evidence, fix, blocker=blocker)
35
27
 
36
28
 
37
29
  def _name(ctx: ProjectContext, path: Path) -> str:
@@ -46,18 +38,17 @@ def _pipeline(ctx: ProjectContext, path: Path) -> CheckResult:
46
38
  check_id = f"correctness.pipeline:{name}"
47
39
  try:
48
40
  load_pipeline(path)
41
+ except MissingEnvError as e:
42
+ return _result(
43
+ check_id,
44
+ 2,
45
+ Status.WARN,
46
+ name,
47
+ f"could not fully validate: {e}",
48
+ "set the variable in this shell to validate the whole spec",
49
+ )
49
50
  except ArsenalError as e:
50
- message = str(e)
51
- if message.startswith(_ENV_NOT_SET):
52
- return _result(
53
- check_id,
54
- 2,
55
- Status.WARN,
56
- name,
57
- f"could not fully validate: {message}",
58
- "set the variable in this shell to validate the whole spec",
59
- )
60
- return _result(check_id, 2, Status.FAIL, name, message, "fix the field the message names")
51
+ return _result(check_id, 2, Status.FAIL, name, str(e), "fix the field the message names")
61
52
  return _result(check_id, 2, Status.PASS, name, "spec is valid")
62
53
 
63
54
 
@@ -0,0 +1,145 @@
1
+ """Is the data itself sound: rows, key uniqueness, NULLs and the period it covers?"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import timedelta
6
+ from typing import Final
7
+
8
+ from censor.model import CheckResult, Dimension, Status
9
+ from censor.reading import DataReading, Profile
10
+ from censor.result import make_result
11
+ from censor.target import AuditContext
12
+
13
+ NULL_WARN_RATIO: Final = 0.5 # half of a column missing deserves a look
14
+ NULL_FAIL_RATIO: Final = 1.0 # a column with no value at all carries no data
15
+ FUTURE_TOLERANCE: Final = timedelta(days=1)
16
+ _DIM: Final = Dimension.DATA_HEALTH
17
+ _WORST_SHOWN: Final = 3
18
+
19
+
20
+ def _r(
21
+ kind: str, reading: DataReading, weight: int, status: Status, evidence: str, fix: str = ""
22
+ ) -> CheckResult:
23
+ check_id = f"data_health.{kind}:{reading.label}"
24
+ return make_result(check_id, _DIM, weight, status, reading.label, evidence, fix)
25
+
26
+
27
+ def _rows(reading: DataReading, profile: Profile) -> CheckResult:
28
+ sampled = " in the sample" if reading.sample else ""
29
+ if profile.rows == 0 and reading.sample:
30
+ evidence = f"the sample is empty ({reading.sample}): nothing to measure"
31
+ return _r("rows", reading, 2, Status.NA, evidence)
32
+ if profile.rows == 0:
33
+ fix = "check that the pipeline wrote output and that the path or table is the right one"
34
+ return _r("rows", reading, 2, Status.FAIL, f"0 rows{sampled}", fix)
35
+ return _r("rows", reading, 2, Status.PASS, f"{profile.rows:,} rows{sampled}")
36
+
37
+
38
+ def _key_checks(reading: DataReading, profile: Profile) -> list[CheckResult]:
39
+ if not reading.key:
40
+ reason = "no key given: pass --key to check uniqueness"
41
+ return [
42
+ _r("key_unique", reading, 3, Status.NA, reason),
43
+ _r("key_not_null", reading, 2, Status.NA, reason),
44
+ ]
45
+ key = ", ".join(reading.key)
46
+ duplicates = profile.duplicate_keys or 0
47
+ if duplicates:
48
+ where = " in the sample" if reading.sample else ""
49
+ unique = _r(
50
+ "key_unique",
51
+ reading,
52
+ 3,
53
+ Status.FAIL,
54
+ f"{duplicates:,} values of ({key}) occur more than once{where}",
55
+ "deduplicate on the key (a `dedup` step, or a sink that upserts on `merge_key`)",
56
+ )
57
+ elif reading.sample:
58
+ unique = _r(
59
+ "key_unique",
60
+ reading,
61
+ 3,
62
+ Status.WARN,
63
+ f"no duplicate ({key}) found in the sample: passes on the sample only",
64
+ "run with --full, or --since on a recent period, to prove uniqueness",
65
+ )
66
+ else:
67
+ unique = _r("key_unique", reading, 3, Status.PASS, f"({key}) is unique")
68
+ null_rows = profile.key_null_rows or 0
69
+ not_null = _r(
70
+ "key_not_null",
71
+ reading,
72
+ 2,
73
+ Status.FAIL if null_rows else Status.PASS,
74
+ f"{null_rows:,} rows have a NULL in ({key})" if null_rows else f"({key}) is never NULL",
75
+ "add `not_null: true` for the key to `validate.rules`, and fix the source rows",
76
+ )
77
+ return [unique, not_null]
78
+
79
+
80
+ def _null_ratio(reading: DataReading, profile: Profile) -> CheckResult:
81
+ ratios = sorted(
82
+ (
83
+ (count / profile.rows, column)
84
+ for column, count in profile.null_counts.items()
85
+ if column not in reading.key
86
+ ),
87
+ key=lambda pair: (-pair[0], pair[1]),
88
+ )
89
+ flagged = [(ratio, column) for ratio, column in ratios if ratio >= NULL_WARN_RATIO]
90
+ if not flagged:
91
+ worst = f"highest: {ratios[0][1]} {ratios[0][0]:.1%}" if ratios else "no other column"
92
+ evidence = f"no column is {NULL_WARN_RATIO:.0%} NULL or more ({worst})"
93
+ return _r("null_ratio", reading, 2, Status.PASS, evidence)
94
+ status = Status.FAIL if flagged[0][0] >= NULL_FAIL_RATIO else Status.WARN
95
+ shown = ", ".join(f"{column} {ratio:.1%}" for ratio, column in flagged[:_WORST_SHOWN])
96
+ more = f" and {len(flagged) - _WORST_SHOWN} more" if len(flagged) > _WORST_SHOWN else ""
97
+ return _r(
98
+ "null_ratio",
99
+ reading,
100
+ 2,
101
+ status,
102
+ f"NULL ratio: {shown}{more}",
103
+ "drop the empty column or fix its mapping; add a `not_null` rule where a value is required",
104
+ )
105
+
106
+
107
+ def _period(ctx: AuditContext, reading: DataReading, profile: Profile) -> CheckResult:
108
+ column = reading.time_column
109
+ if column is None:
110
+ return _r("period", reading, 1, Status.NA, "no time column given: pass --time-column")
111
+ if profile.time_min is None or profile.time_max is None:
112
+ fix = "check the column name and that the source fills it"
113
+ return _r("period", reading, 1, Status.FAIL, f"{column} is NULL in every row", fix)
114
+ span = f"{column} from {profile.time_min} to {profile.time_max}"
115
+ if profile.time_max_at is not None and profile.time_max_at > ctx.now + FUTURE_TOLERANCE:
116
+ fix = "check the time zone and unit of the column (seconds vs milliseconds)"
117
+ return _r(
118
+ "period", reading, 1, Status.WARN, f"{span}: the newest value is in the future", fix
119
+ )
120
+ return _r("period", reading, 1, Status.PASS, span)
121
+
122
+
123
+ def _reading(ctx: AuditContext, reading: DataReading) -> list[CheckResult]:
124
+ if reading.failure is not None:
125
+ fix = "check the column types; report this with the evidence if the data looks right"
126
+ return [_r("profile", reading, 1, Status.ERROR, reading.failure, fix)]
127
+ profile = reading.profile
128
+ if profile is None:
129
+ return [_r("skipped", reading, 1, Status.NA, reading.skipped or "not profiled")]
130
+ results = [_rows(reading, profile)]
131
+ if profile.rows == 0:
132
+ return results
133
+ return [
134
+ *results,
135
+ *_key_checks(reading, profile),
136
+ _null_ratio(reading, profile),
137
+ _period(ctx, reading, profile),
138
+ ]
139
+
140
+
141
+ def check_data_health(ctx: AuditContext) -> list[CheckResult]:
142
+ results: list[CheckResult] = []
143
+ for reading in ctx.readings:
144
+ results.extend(_reading(ctx, reading))
145
+ return results