File size: 5,776 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""Content-addressed hashing utilities.

All hashes are lowercase hexadecimal SHA-256. The canonical ID of a source item
(``base_id``) is a content-addressed hash over its source identity plus its
question, choices, and image family (``docs/02_DATA_PIPELINE.md`` §3.1), never a
human-readable string. Question and choice hashes operate on the exact UTF-8
source bytes; the model input string is never normalized or rewritten.
"""

from __future__ import annotations

import hashlib
import json
from collections.abc import Iterable, Mapping, Sequence
from pathlib import Path
from typing import Any

HEX_SHA256_LEN = 64
GIT_REVISION_LEN = 40


def sha256_bytes(data: bytes) -> str:
    """Return the lowercase hex SHA-256 of ``data``."""
    return hashlib.sha256(data).hexdigest()


def sha256_text(text: str) -> str:
    """Return the lowercase hex SHA-256 of the UTF-8 encoding of ``text``."""
    return sha256_bytes(text.encode("utf-8"))


def sha256_file(path: str | Path, *, chunk_size: int = 1 << 20) -> str:
    """Stream ``path`` and return its lowercase hex SHA-256."""
    digest = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for chunk in iter(lambda: handle.read(chunk_size), b""):
            digest.update(chunk)
    return digest.hexdigest()


def is_sha256(value: str) -> bool:
    """True when ``value`` is a 64-char lowercase hex SHA-256 string."""
    return len(value) == HEX_SHA256_LEN and all(c in "0123456789abcdef" for c in value)


def is_git_revision(value: str) -> bool:
    """True when ``value`` is a 40-char lowercase hex git revision."""
    return len(value) == GIT_REVISION_LEN and all(c in "0123456789abcdef" for c in value)


def canonical_json(obj: Any) -> str:
    """Serialize ``obj`` to deterministic JSON.

    Object keys are sorted; whitespace is removed; Unicode is preserved. Array
    order is preserved (list order is significant for choices and images).
    """
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def canonical_json_hash(obj: Any) -> str:
    """SHA-256 of :func:`canonical_json` (machine/path independent)."""
    return sha256_text(canonical_json(obj))


def canonical_config_hash(config: Any) -> str:
    """Hash a parsed config object independent of file path or machine.

    Accepts a loaded mapping (e.g. ``yaml.safe_load`` output) or any
    JSON-serializable object. Because the hash is over canonical content rather
    than a file path, the same config yields the same hash everywhere.
    """
    if isinstance(config, str):
        raise TypeError("pass a parsed config object, not a path string")
    return canonical_json_hash(config)


def image_family_sha256(image_sha256: Sequence[str]) -> str:
    """SHA-256 over the canonical-JSON of a content item's image *family*.

    The family is the set of image SHA-256 digests attached to one item, taken
    order-independently (``docs/02`` §3.1). Sorting makes the hash insensitive
    to image ordering, so the same set of images yields the same family hash.
    A text-only item (no images) hashes the empty list.
    """
    return sha256_text(canonical_json(sorted(image_sha256)))


def base_id(
    *,
    source: str,
    source_revision: str,
    source_native_id: str,
    image_family_sha256: str,
    question_sha256: str,
    choices_sha256: str,
) -> str:
    """Compute the canonical ``base_id`` of a source item (``docs/02`` §3.1).

    ``base_id = sha256(canonical_json({source, source_revision,
    source_native_id, image_family_sha256, question_sha256, choices_sha256}))``.

    The ID is **content-addressed**: it folds the item's question, choices, and
    image family together with its source identity. ``source_config`` and
    ``source_split`` are deliberately excluded — an item's identity must not
    change merely because it is filed under a different config or split, or
    train/eval collision detection would miss a train row and its eval twin.
    Canonical JSON (sorted keys, compact separators) prevents field-bleed
    collisions without a manual separator.
    """
    return canonical_json_hash(
        {
            "source": source,
            "source_revision": source_revision,
            "source_native_id": str(source_native_id),
            "image_family_sha256": image_family_sha256,
            "question_sha256": question_sha256,
            "choices_sha256": choices_sha256,
        }
    )


def _choices_as_records(choices: Sequence[Any]) -> list[dict[str, str]]:
    records: list[dict[str, str]] = []
    for choice in choices:
        if isinstance(choice, Mapping):
            records.append({"key": str(choice["key"]), "text": str(choice["text"])})
        else:
            raise TypeError(f"choice must be a mapping with 'key' and 'text', got {type(choice)!r}")
    return records


def choices_canonical_json(choices: Sequence[Any]) -> str:
    """Canonical JSON of choices in source order: ``[{"key":..,"text":..}, ...]``."""
    return canonical_json(_choices_as_records(choices))


def question_sha256(question: str) -> str:
    """SHA-256 over the exact UTF-8 question bytes."""
    return sha256_text(question)


def choices_sha256(choices: Sequence[Any]) -> str:
    """SHA-256 over the canonical-JSON serialization of choices in source order."""
    return sha256_text(choices_canonical_json(choices))


def join_manifest_sha256(entries: Iterable[str]) -> str:
    """Hash an ordered collection of manifest/row SHA-256 digests into one digest.

    Used to fold a stage's per-row hashes into a single input manifest hash for
    the next stage.
    """
    digest = hashlib.sha256()
    for entry in entries:
        digest.update(entry.encode("ascii"))
        digest.update(b"\n")
    return digest.hexdigest()