Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ __pycache__/
micro/us/*.parquet
venv/
*.parquet
.hypothesis/
# Raw releases archived in R2 only (chronicle#343); each manifest pins the bytes.
# Price Paid Data carries Royal Mail and OS address data licensed for
# non-commercial use, so none of its bytes enter this public repository; the
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,19 @@ This writes queryable Chronicle-owned tables such as `source_rows`,
manifests, parsers, and checked-in specs; hosted Postgres/Supabase should mirror
this schema rather than become the unreproducible origin of source-backed facts.

On the same Python and SQLite build, identical inputs write a byte-identical
`ledger.db`, so a rebuilt suite's `ledger.db`, `datapackage.json` and
`ro-crate-metadata.json` can be checked against published ones by sha256. (The
SQLite file header records the library version that wrote it.) Writing
`ledger.db` never reads the clock:
`ledger_builds.created_at` is taken from
[`SOURCE_DATE_EPOCH`](https://reproducible-builds.org/specs/source-date-epoch/)
(Unix seconds) when it is set and is the Unix epoch otherwise, and a malformed
value fails the build before any output is touched. To reproduce a build
stamped with another time, set `SOURCE_DATE_EPOCH` to its `created_at` in Unix
seconds. Reports record absolute output paths, so compare rebuilds made at the
same `--out` path.

To run the source-package build suite agents should target, build the source
rows/cells, source-region spec, selector report, aggregate facts, DB artifact,
and JSON reports into one output directory:
Expand Down
1 change: 1 addition & 0 deletions changelog.d/316.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Write `ledger.db` byte-reproducibly: `ledger_builds.created_at` follows `SOURCE_DATE_EPOCH` (default the Unix epoch) instead of the wall clock, so a rebuilt suite matches the published `ledger.db`, `datapackage.json` and `ro-crate-metadata.json` hashes.
2 changes: 2 additions & 0 deletions chronicle/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from pathlib import Path
from typing import Any, Callable, Iterable, Sequence

from chronicle.database import build_created_at
from chronicle.dimension_labels import (
cross_package_value_label_remedy,
dimension_label_issues,
Expand Down Expand Up @@ -830,6 +831,7 @@ def build_bundle(
replace: bool = False,
) -> BuildBundleReport:
"""Build source-package suites and merge their consumer-contract facts."""
build_created_at() # Refuse a malformed SOURCE_DATE_EPOCH before writing.
output_path = Path(output_dir)
_prepare_output_dir(output_path, replace=replace)
reports_path = output_path / "reports"
Expand Down
59 changes: 56 additions & 3 deletions chronicle/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@

The database is a Chronicle-owned query surface for source-backed aggregate facts.
It is deterministic output from source artifacts, selectors, and aggregate facts;
hosted systems such as Supabase can mirror this schema later.
hosted systems such as Supabase can mirror this schema later. With the same
Python and SQLite build, identical inputs give byte-identical files:
``ledger_builds.created_at`` comes from ``SOURCE_DATE_EPOCH``, never the wall
clock.
"""

from __future__ import annotations

import hashlib
import json
import os
import re
import sqlite3
from collections.abc import Mapping
from contextlib import closing
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -42,6 +48,11 @@
)

LEDGER_DB_SCHEMA_VERSION = schema_id("relational", Epoch.LEDGER)
SOURCE_DATE_EPOCH_ENV = "SOURCE_DATE_EPOCH"
_MAX_SOURCE_DATE_EPOCH = 253_402_300_799 # 9999-12-31T23:59:59Z
# Unix seconds as ``date +%s`` prints them: no sign, no leading zeros.
_SOURCE_DATE_EPOCH_PATTERN = re.compile(r"0|[1-9][0-9]{0,11}")
_UNIX_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)


@dataclass(frozen=True)
Expand Down Expand Up @@ -72,13 +83,19 @@ def build_chronicle_db(
build_id: str | None = None,
replace: bool = False,
emit_epoch: Epoch | str = EMIT_EPOCH,
source_date_epoch: int | None = None,
) -> ChronicleDbBuildReport:
"""Build a deterministic SQLite Chronicle database artifact.

``emit_epoch`` may be the enum member or its string value. An explicit
``build_id`` must carry an accepted build-domain prefix; it is validated
before the filesystem is touched so a refused call leaves an existing
database in place.

``ledger_builds.created_at`` is ``source_date_epoch`` (Unix seconds) when
given, else the ``SOURCE_DATE_EPOCH`` environment variable, else the Unix
epoch, so the same inputs always write the same bytes. A malformed value
is refused before the filesystem is touched.
"""
try:
emit_epoch = Epoch(emit_epoch)
Expand All @@ -96,6 +113,7 @@ def build_chronicle_db(
if build_id is not None
else _build_id(facts, cells, rows, epoch=emit_epoch)
)
created_at = build_created_at(source_date_epoch)

path = Path(db_path)
if path.exists():
Expand All @@ -120,6 +138,7 @@ def build_chronicle_db(
_insert_build(
connection,
build_id=resolved_build_id,
created_at=created_at,
facts_count=len(facts),
constraints_count=sum(
len(constraints) for _, constraints in fact_constraints
Expand Down Expand Up @@ -420,10 +439,44 @@ def _create_indexes(connection: sqlite3.Connection) -> None:
)


def build_created_at(
source_date_epoch: int | None = None,
environ: Mapping[str, str] | None = None,
) -> str:
"""Return the ISO-8601 UTC build time for ``ledger_builds.created_at``.

An explicit ``source_date_epoch`` wins, then ``SOURCE_DATE_EPOCH`` in
``environ`` (the process environment by default), formatted as
https://reproducible-builds.org/specs/source-date-epoch/ requires; when
neither is set the build is stamped with the Unix epoch. Builds call it
before touching their output so a malformed value refuses the build.
"""
name = "source_date_epoch"
value: object = source_date_epoch
if value is None:
name = SOURCE_DATE_EPOCH_ENV
environ = os.environ if environ is None else environ
raw = environ.get(SOURCE_DATE_EPOCH_ENV, "0")
value = int(raw) if _SOURCE_DATE_EPOCH_PATTERN.fullmatch(raw) else raw
if (
not isinstance(value, int)
or isinstance(value, bool)
or not 0 <= value <= _MAX_SOURCE_DATE_EPOCH
):
raise ValueError(
f"{name} must be an integer count of Unix seconds from 0 to "
f"{_MAX_SOURCE_DATE_EPOCH}; got {value!r}"
)
# Epoch arithmetic, unlike datetime.fromtimestamp, reaches year 9999 on
# every platform.
return (_UNIX_EPOCH + timedelta(seconds=value)).isoformat()


def _insert_build(
connection: sqlite3.Connection,
*,
build_id: str,
created_at: str,
facts_count: int,
constraints_count: int,
source_records_count: int,
Expand Down Expand Up @@ -454,7 +507,7 @@ def _insert_build(
(
build_id,
schema_id("relational", emit_epoch),
datetime.now(timezone.utc).isoformat(),
created_at,
facts_count,
constraints_count,
source_records_count,
Expand Down
7 changes: 6 additions & 1 deletion chronicle/suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@
build_fact_key,
validate_facts,
)
from chronicle.database import ChronicleDbBuildReport, build_chronicle_db
from chronicle.database import (
ChronicleDbBuildReport,
build_chronicle_db,
build_created_at,
)
from chronicle.epoch import canonicalize_key
from chronicle.sources.cells import (
SourceArtifactMetadata,
Expand Down Expand Up @@ -293,6 +297,7 @@ def build_source_suite(
replace: bool = False,
) -> BuildSuiteReport:
"""Build all reproducible Chronicle artifacts and reports for a source package."""
build_created_at() # Refuse a malformed SOURCE_DATE_EPOCH before writing.
source_package = try_load_source_package(source)
source_id = source_package.package_id if source_package else source
output_path = Path(output_dir)
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ dependencies = [

[project.optional-dependencies]
dev = [
"hypothesis>=6",
"pytest>=8.0.0,<9",
"ruff>=0.5.0",
]
Expand Down Expand Up @@ -58,5 +59,6 @@ target-version = "py311"

[dependency-groups]
dev = [
"hypothesis>=6",
"pytest>=8.0.0,<9",
]
Loading
Loading