ucde 0.2.0__py3-none-any.whl
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.
- ucde/__init__.py +20 -0
- ucde/__main__.py +7 -0
- ucde/archive.py +109 -0
- ucde/chain.py +222 -0
- ucde/chain_audit.py +210 -0
- ucde/cli.py +363 -0
- ucde/crate.py +98 -0
- ucde/mcp_server.py +230 -0
- ucde/model.py +192 -0
- ucde/ollama.py +183 -0
- ucde/packet.py +250 -0
- ucde/provenance.py +101 -0
- ucde/py.typed +0 -0
- ucde/ranking.py +98 -0
- ucde/store.py +729 -0
- ucde-0.2.0.dist-info/METADATA +171 -0
- ucde-0.2.0.dist-info/RECORD +21 -0
- ucde-0.2.0.dist-info/WHEEL +5 -0
- ucde-0.2.0.dist-info/entry_points.txt +3 -0
- ucde-0.2.0.dist-info/licenses/LICENSE +202 -0
- ucde-0.2.0.dist-info/top_level.txt +1 -0
ucde/packet.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Portable receipts for scoped historical evidence searches."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from hashlib import sha256
|
|
6
|
+
from hmac import compare_digest
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .model import Evidence, ValidationError, bounded_integer, checked_context, checked_text, timestamp, validated_evidence
|
|
12
|
+
from .ranking import STRATEGIES
|
|
13
|
+
from .store import MemoryStore
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
PACKET_FORMAT = "ucde.evidence-packet.v1"
|
|
17
|
+
PACKET_MAX_BYTES = 128 * 1024 * 1024
|
|
18
|
+
PACKET_STRATEGIES = STRATEGIES - {"dense"}
|
|
19
|
+
_CITATION_FIELDS = {"source", "locator", "source_sha256"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _canonical_json(value: object) -> str:
|
|
23
|
+
return json.dumps(value, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(",", ":"))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _digest(document: dict[str, Any]) -> str:
|
|
27
|
+
try:
|
|
28
|
+
return sha256(_canonical_json(document).encode("utf-8")).hexdigest()
|
|
29
|
+
except (ValueError, RecursionError) as error:
|
|
30
|
+
raise ValidationError("packet must contain finite JSON values and valid Unicode") from error
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _checked_digest(value: object, name: str) -> str:
|
|
34
|
+
if not isinstance(value, str) or re.fullmatch(r"[0-9a-fA-F]{64}", value) is None:
|
|
35
|
+
raise ValidationError(f"{name} must be a 64-character hexadecimal digest")
|
|
36
|
+
return value.lower()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
40
|
+
result: dict[str, Any] = {}
|
|
41
|
+
for key, value in pairs:
|
|
42
|
+
if key in result:
|
|
43
|
+
raise ValidationError("packet JSON contains a duplicate object key")
|
|
44
|
+
result[key] = value
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _invalid_constant(value: str) -> None:
|
|
49
|
+
raise ValidationError(f"packet JSON contains an invalid number: {value}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _fields(value: object, fields: set[str], name: str) -> dict[str, Any]:
|
|
53
|
+
if not isinstance(value, dict) or set(value) != fields:
|
|
54
|
+
raise ValidationError(f"invalid packet {name} fields")
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _validate_payload(payload: object) -> None:
|
|
59
|
+
body = _fields(payload, {"request", "result"}, "payload")
|
|
60
|
+
request = _fields(body["request"], {
|
|
61
|
+
"query", "known_at", "observed_after", "observed_before", "target_at", "context", "subject",
|
|
62
|
+
"variable", "method", "scale", "strategy", "limit", "candidate_limit",
|
|
63
|
+
}, "request")
|
|
64
|
+
known = timestamp(request["known_at"], "known_at")
|
|
65
|
+
if request["query"] != "":
|
|
66
|
+
checked_text(request["query"], "query", 4096)
|
|
67
|
+
limit = bounded_integer(request["limit"], "limit", 1, 200)
|
|
68
|
+
result = _fields(body["result"], {"hits", "lexical_candidates", "dense_candidates", "vector_scan_truncated"}, "result")
|
|
69
|
+
if not isinstance(result["hits"], list) or len(result["hits"]) > limit:
|
|
70
|
+
raise ValidationError("invalid packet hits")
|
|
71
|
+
seen_ids: set[str] = set()
|
|
72
|
+
for item in result["hits"]:
|
|
73
|
+
hit = _fields(item, {"revision", "score", "lexical_rank", "dense_similarity", "temporal", "quality"}, "hit")
|
|
74
|
+
revision = _fields(hit["revision"], {"evidence", "revision", "recorded_at", "retracted", "restored_from"}, "revision")
|
|
75
|
+
if revision["retracted"] is not False or timestamp(revision["recorded_at"], "recorded_at") > known:
|
|
76
|
+
raise ValidationError("packet record must be active at the recording cutoff")
|
|
77
|
+
evidence = _fields(revision["evidence"], {
|
|
78
|
+
"id", "text", "subject", "variable", "method", "scale", "observed_at", "source", "locator",
|
|
79
|
+
"context", "confidence", "importance", "source_sha256",
|
|
80
|
+
}, "evidence")
|
|
81
|
+
validated_evidence(Evidence(**evidence))
|
|
82
|
+
identifier = evidence["id"]
|
|
83
|
+
if identifier in seen_ids:
|
|
84
|
+
raise ValidationError(f"duplicate evidence ID in packet: {identifier}")
|
|
85
|
+
seen_ids.add(identifier)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def export_packet(
|
|
89
|
+
store: MemoryStore, query: str, *, known_at: datetime | str,
|
|
90
|
+
context: dict[str, str] | None = None, subject: str | None = None, variable: str | None = None,
|
|
91
|
+
method: str | None = None, scale: str | None = None, observed_after: datetime | str | None = None,
|
|
92
|
+
observed_before: datetime | str | None = None, target_at: datetime | str | None = None,
|
|
93
|
+
strategy: str = "adaptive", limit: int = 10, candidate_limit: int = 200,
|
|
94
|
+
) -> dict[str, Any]:
|
|
95
|
+
"""Capture the ordered results of one text search at an explicit recording cutoff."""
|
|
96
|
+
if not isinstance(strategy, str) or strategy not in PACKET_STRATEGIES:
|
|
97
|
+
raise ValidationError("evidence packets require a text search strategy")
|
|
98
|
+
known = timestamp(known_at, "known_at")
|
|
99
|
+
lower = timestamp(observed_after, "observed_after") if observed_after is not None else None
|
|
100
|
+
upper = timestamp(observed_before, "observed_before") if observed_before is not None else None
|
|
101
|
+
target = timestamp(target_at, "target_at") if target_at is not None else None
|
|
102
|
+
scope = checked_context(context) if context is not None else {}
|
|
103
|
+
result = asdict(store.search(
|
|
104
|
+
query, known_at=known, context=scope, subject=subject, variable=variable, method=method, scale=scale,
|
|
105
|
+
observed_after=lower, observed_before=upper, target_at=target, strategy=strategy,
|
|
106
|
+
limit=limit, candidate_limit=candidate_limit,
|
|
107
|
+
))
|
|
108
|
+
result["hits"] = list(result["hits"])
|
|
109
|
+
for hit in result["hits"]:
|
|
110
|
+
evidence = hit["revision"]["evidence"]
|
|
111
|
+
del evidence["embedding"], evidence["embedding_space"]
|
|
112
|
+
request = {
|
|
113
|
+
"query": query, "known_at": known, "observed_after": lower, "observed_before": upper, "target_at": target,
|
|
114
|
+
"context": scope, "subject": subject, "variable": variable, "method": method,
|
|
115
|
+
"scale": scale, "strategy": strategy, "limit": limit, "candidate_limit": candidate_limit,
|
|
116
|
+
}
|
|
117
|
+
document = {"format": PACKET_FORMAT, "payload": {"request": request, "result": result}}
|
|
118
|
+
return {**document, "sha256": _digest(document)}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def verify_packet(raw: bytes | str, *, expected_sha256: str | None = None) -> dict[str, Any]:
|
|
122
|
+
"""Read a packet and verify its content digest, optionally against an independent digest."""
|
|
123
|
+
if not isinstance(raw, (bytes, str)):
|
|
124
|
+
raise ValidationError("packet input must be UTF-8 bytes or text")
|
|
125
|
+
try:
|
|
126
|
+
if len(raw) > PACKET_MAX_BYTES or (isinstance(raw, str) and len(raw.encode("utf-8")) > PACKET_MAX_BYTES):
|
|
127
|
+
raise ValidationError("packet exceeds the input size limit")
|
|
128
|
+
text = raw.decode("utf-8-sig") if isinstance(raw, bytes) else raw.removeprefix("\ufeff")
|
|
129
|
+
envelope = json.loads(text, object_pairs_hook=_unique_object, parse_constant=_invalid_constant)
|
|
130
|
+
except ValidationError:
|
|
131
|
+
raise
|
|
132
|
+
except (ValueError, RecursionError) as error:
|
|
133
|
+
raise ValidationError("packet must be valid UTF-8 JSON") from error
|
|
134
|
+
envelope = _fields(envelope, {"format", "payload", "sha256"}, "envelope")
|
|
135
|
+
if envelope["format"] != PACKET_FORMAT:
|
|
136
|
+
raise ValidationError("unsupported evidence packet format")
|
|
137
|
+
payload = envelope["payload"]
|
|
138
|
+
stored = _checked_digest(envelope["sha256"], "packet digest")
|
|
139
|
+
actual = _digest({"format": PACKET_FORMAT, "payload": payload})
|
|
140
|
+
if not compare_digest(stored, actual):
|
|
141
|
+
raise ValidationError("packet content digest does not match")
|
|
142
|
+
if expected_sha256 is not None and not compare_digest(_checked_digest(expected_sha256, "expected digest"), actual):
|
|
143
|
+
raise ValidationError("packet digest does not match the expected digest")
|
|
144
|
+
_validate_payload(payload)
|
|
145
|
+
return envelope
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _comparison_input(raw: bytes | str, expected_sha256: str | None, side: str) -> dict[str, Any]:
|
|
149
|
+
try:
|
|
150
|
+
return verify_packet(raw, expected_sha256=expected_sha256)
|
|
151
|
+
except ValidationError as error:
|
|
152
|
+
raise ValidationError(f"{side} packet: {error}") from error
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _positioned_hits(packet: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
|
156
|
+
return {
|
|
157
|
+
hit["revision"]["evidence"]["id"]: {"position": position, **hit}
|
|
158
|
+
for position, hit in enumerate(packet["payload"]["result"]["hits"], start=1)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _packet_reference(packet: dict[str, Any]) -> dict[str, str]:
|
|
163
|
+
request = packet["payload"]["request"]
|
|
164
|
+
return {
|
|
165
|
+
"sha256": packet["sha256"].lower(), "known_at": request["known_at"],
|
|
166
|
+
"effective_observed_before": request["observed_before"] or request["known_at"],
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _hit_reference(hit: dict[str, Any]) -> dict[str, Any]:
|
|
171
|
+
revision = hit["revision"]
|
|
172
|
+
evidence = revision["evidence"]
|
|
173
|
+
return {
|
|
174
|
+
"id": evidence["id"], "position": hit["position"], "revision": revision["revision"],
|
|
175
|
+
"source": evidence["source"], "locator": evidence["locator"], "source_sha256": evidence["source_sha256"],
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _field_changes(before: dict[str, Any], after: dict[str, Any], fields: set[str]) -> dict[str, Any]:
|
|
180
|
+
return {
|
|
181
|
+
field: {"before": before[field], "after": after[field]}
|
|
182
|
+
for field in sorted(fields) if _canonical_json(before[field]) != _canonical_json(after[field])
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _hit_changes(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
|
|
187
|
+
old_revision, new_revision = before["revision"], after["revision"]
|
|
188
|
+
old_evidence, new_evidence = old_revision["evidence"], new_revision["evidence"]
|
|
189
|
+
categories = {
|
|
190
|
+
"evidence": _field_changes(old_evidence, new_evidence, old_evidence.keys() - _CITATION_FIELDS - {"id"}),
|
|
191
|
+
"citation": _field_changes(old_evidence, new_evidence, _CITATION_FIELDS),
|
|
192
|
+
"revision": _field_changes(old_revision, new_revision, old_revision.keys() - {"evidence"}),
|
|
193
|
+
"ranking": _field_changes(before, after, before.keys() - {"revision"}),
|
|
194
|
+
}
|
|
195
|
+
return {name: changes for name, changes in categories.items() if changes}
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _compare_verified(earlier: dict[str, Any], later: dict[str, Any]) -> dict[str, Any]:
|
|
199
|
+
original = _positioned_hits(earlier)
|
|
200
|
+
updated = _positioned_hits(later)
|
|
201
|
+
before_only = [_hit_reference(original[key]) for key in sorted(original.keys() - updated.keys())]
|
|
202
|
+
after_only = [_hit_reference(updated[key]) for key in sorted(updated.keys() - original.keys())]
|
|
203
|
+
changed = []
|
|
204
|
+
unchanged = []
|
|
205
|
+
for identifier in sorted(original.keys() & updated.keys()):
|
|
206
|
+
old_hit, new_hit = original[identifier], updated[identifier]
|
|
207
|
+
changes = _hit_changes(old_hit, new_hit)
|
|
208
|
+
if changes:
|
|
209
|
+
changed.append({
|
|
210
|
+
"id": identifier, "before": _hit_reference(old_hit), "after": _hit_reference(new_hit), "changes": changes,
|
|
211
|
+
})
|
|
212
|
+
else:
|
|
213
|
+
unchanged.append(identifier)
|
|
214
|
+
old_request, new_request = earlier["payload"]["request"], later["payload"]["request"]
|
|
215
|
+
return {
|
|
216
|
+
"format": "ucde.evidence-comparison.v1",
|
|
217
|
+
"before": _packet_reference(earlier), "after": _packet_reference(later),
|
|
218
|
+
"request_changes": _field_changes(old_request, new_request, old_request.keys() - {"known_at"}),
|
|
219
|
+
"counts": {
|
|
220
|
+
"before_only": len(before_only), "after_only": len(after_only), "shared": len(changed) + len(unchanged),
|
|
221
|
+
"changed": len(changed), "unchanged": len(unchanged),
|
|
222
|
+
},
|
|
223
|
+
"before_only": before_only, "after_only": after_only, "changed": changed, "unchanged": unchanged,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def compare_packets(
|
|
228
|
+
before: bytes | str, after: bytes | str, *,
|
|
229
|
+
before_sha256: str | None = None, after_sha256: str | None = None,
|
|
230
|
+
) -> dict[str, Any]:
|
|
231
|
+
"""Verify two packets and describe differences among the records they returned."""
|
|
232
|
+
earlier = _comparison_input(before, before_sha256, "before")
|
|
233
|
+
later = _comparison_input(after, after_sha256, "after")
|
|
234
|
+
return _compare_verified(earlier, later)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def replay_packet(
|
|
238
|
+
store: MemoryStore, raw: bytes | str, *, expected_sha256: str | None = None,
|
|
239
|
+
) -> dict[str, Any]:
|
|
240
|
+
"""Rerun a verified packet's exact search and compare it with the retained ledger."""
|
|
241
|
+
archived = verify_packet(raw, expected_sha256=expected_sha256)
|
|
242
|
+
replayed = export_packet(store, **archived["payload"]["request"])
|
|
243
|
+
original_result = archived["payload"]["result"]
|
|
244
|
+
replayed_result = replayed["payload"]["result"]
|
|
245
|
+
return {
|
|
246
|
+
"format": "ucde.evidence-replay.v1",
|
|
247
|
+
"matched": compare_digest(archived["sha256"].lower(), replayed["sha256"]),
|
|
248
|
+
"comparison": _compare_verified(archived, replayed),
|
|
249
|
+
"result_changes": _field_changes(original_result, replayed_result, original_result.keys() - {"hits"}),
|
|
250
|
+
}
|
ucde/provenance.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Deterministic PROV-O projection of retained UCDE revision history."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from hashlib import sha256
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import BinaryIO
|
|
8
|
+
|
|
9
|
+
from .archive import CHECKPOINT_FORMAT, _normalized_timestamp, _read_frame, _revision_key, checkpoint_line
|
|
10
|
+
from .model import ValidationError, checked_sha256, checked_text
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_CONTEXT = {
|
|
14
|
+
"prov": "http://www.w3.org/ns/prov#",
|
|
15
|
+
"ucde": "https://github.com/mqfarooqi1/ucde#",
|
|
16
|
+
"xsd": "http://www.w3.org/2001/XMLSchema#",
|
|
17
|
+
}
|
|
18
|
+
_HISTORY = "history.jsonl"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _reference(identifier: str) -> dict[str, str]:
|
|
22
|
+
return {"@id": identifier}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _date_time(value: str) -> dict[str, str]:
|
|
26
|
+
return {"@value": value, "@type": "xsd:dateTime"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _citation(payload: dict[str, object]) -> tuple[str, dict[str, object]]:
|
|
30
|
+
source = checked_text(payload.get("source"), "archive citation source")
|
|
31
|
+
locator = checked_text(payload.get("locator"), "archive citation locator")
|
|
32
|
+
digest = payload.get("source_sha256")
|
|
33
|
+
if digest is not None:
|
|
34
|
+
checked_sha256(digest, "archive citation digest")
|
|
35
|
+
identifier = "#citation-" + sha256(checkpoint_line((source, locator, digest))).hexdigest()
|
|
36
|
+
entity: dict[str, object] = {
|
|
37
|
+
"@id": identifier, "@type": "prov:Entity", "ucde:source": source, "ucde:locator": locator,
|
|
38
|
+
}
|
|
39
|
+
if isinstance(digest, str):
|
|
40
|
+
entity["ucde:sourceSha256"] = digest
|
|
41
|
+
return identifier, entity
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _archive_entities(source: BinaryIO) -> Iterator[dict[str, object]]:
|
|
45
|
+
header = _read_frame(source)
|
|
46
|
+
if header is None or len(header[1]) != 2 or header[1][0] != CHECKPOINT_FORMAT:
|
|
47
|
+
raise ValidationError("provenance requires a UCDE history archive")
|
|
48
|
+
cutoff = _normalized_timestamp(header[1][1], "archive cutoff")
|
|
49
|
+
yield {"@id": _HISTORY, "@type": "prov:Collection", "ucde:knownAt": _date_time(cutoff)}
|
|
50
|
+
|
|
51
|
+
current_id: str | None = None
|
|
52
|
+
observation_id = revision_prefix = ""
|
|
53
|
+
retained_revisions: set[int] = set()
|
|
54
|
+
while frame := _read_frame(source):
|
|
55
|
+
_, values = frame
|
|
56
|
+
identifier, revision = _revision_key(values, cutoff)
|
|
57
|
+
_, _, recorded, observed, retracted, restored, payload, _, _ = values
|
|
58
|
+
if identifier != current_id:
|
|
59
|
+
current_id = identifier
|
|
60
|
+
token = sha256(identifier.encode("utf-8")).hexdigest()
|
|
61
|
+
observation_id = f"#observation-{token}"
|
|
62
|
+
revision_prefix = f"#revision-{token}-"
|
|
63
|
+
retained_revisions.clear()
|
|
64
|
+
yield {"@id": observation_id, "@type": "prov:Entity", "ucde:observationId": identifier}
|
|
65
|
+
|
|
66
|
+
citation_id, citation = _citation(json.loads(payload))
|
|
67
|
+
yield citation
|
|
68
|
+
derivations = [_reference(citation_id)]
|
|
69
|
+
entity: dict[str, object] = {
|
|
70
|
+
"@id": f"{revision_prefix}{revision}",
|
|
71
|
+
"@type": "prov:Entity",
|
|
72
|
+
"@reverse": {"prov:hadMember": _reference(_HISTORY)},
|
|
73
|
+
"prov:specializationOf": _reference(observation_id),
|
|
74
|
+
"prov:generatedAtTime": _date_time(recorded),
|
|
75
|
+
"prov:wasDerivedFrom": derivations,
|
|
76
|
+
"ucde:revision": revision,
|
|
77
|
+
"ucde:observedAt": _date_time(observed),
|
|
78
|
+
"ucde:retracted": bool(retracted),
|
|
79
|
+
}
|
|
80
|
+
if restored is not None:
|
|
81
|
+
entity["ucde:restoredFromRevision"] = restored
|
|
82
|
+
if restored in retained_revisions:
|
|
83
|
+
origin = _reference(f"{revision_prefix}{restored}")
|
|
84
|
+
entity["ucde:restoredFrom"] = origin
|
|
85
|
+
derivations.append(origin)
|
|
86
|
+
elif revision - 1 in retained_revisions:
|
|
87
|
+
entity["prov:wasRevisionOf"] = _reference(f"{revision_prefix}{revision - 1}")
|
|
88
|
+
yield entity
|
|
89
|
+
retained_revisions.add(revision)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def write_provenance(archive_path: Path, destination: Path) -> None:
|
|
93
|
+
"""Stream the provenance graph of an independently verified history archive."""
|
|
94
|
+
with archive_path.open("rb") as source, destination.open("x", encoding="utf-8", newline="\n") as output:
|
|
95
|
+
context = json.dumps(_CONTEXT, ensure_ascii=False, separators=(",", ":"))
|
|
96
|
+
output.write(f'{{"@context":{context},"@graph":[\n')
|
|
97
|
+
for index, entity in enumerate(_archive_entities(source)):
|
|
98
|
+
if index:
|
|
99
|
+
output.write(",\n")
|
|
100
|
+
output.write(json.dumps(entity, ensure_ascii=False, allow_nan=False, separators=(",", ":")))
|
|
101
|
+
output.write("\n]}\n")
|
ucde/py.typed
ADDED
|
File without changes
|
ucde/ranking.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Deterministic ranking rules with a shared set of candidates."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime, timedelta
|
|
5
|
+
from math import fsum, log1p
|
|
6
|
+
import re
|
|
7
|
+
import unicodedata
|
|
8
|
+
|
|
9
|
+
from .model import Revision, SearchHit
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
STRATEGIES = frozenset({"adaptive", "lexical", "recent", "dense", "rrf", "no-time", "no-quality", "nearest"})
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True)
|
|
16
|
+
class Candidate:
|
|
17
|
+
revision: Revision
|
|
18
|
+
lexical_rank: int | None = None
|
|
19
|
+
dense_similarity: float | None = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def tokens(text: str) -> list[str]:
|
|
23
|
+
normalized = unicodedata.normalize("NFKD", text.casefold())
|
|
24
|
+
stripped = "".join(character for character in normalized if not unicodedata.combining(character))
|
|
25
|
+
return re.findall(r"[^\W_]+", stripped)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def bm25(counts: dict[str, int], length: int, average: float, documents: int,
|
|
29
|
+
document_frequencies: dict[str, int]) -> float:
|
|
30
|
+
normalizer = 1.2 * (0.25 + 0.75 * length / average)
|
|
31
|
+
return fsum(
|
|
32
|
+
log1p((documents - document_frequencies[term] + 0.5) / (document_frequencies[term] + 0.5))
|
|
33
|
+
* 2.2 * frequency / (frequency + normalizer)
|
|
34
|
+
for term, frequency in counts.items()
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def date_distance(observed: datetime | str, target: datetime) -> timedelta:
|
|
39
|
+
moment = datetime.fromisoformat(observed) if isinstance(observed, str) else observed
|
|
40
|
+
return abs(moment - target)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _nearest(candidates: list[Candidate], target: datetime) -> list[SearchHit]:
|
|
44
|
+
distances = [(date_distance(item.revision.evidence.observed_at, target), item) for item in candidates]
|
|
45
|
+
distances.sort(key=lambda entry: (entry[0], entry[1].lexical_rank or float("inf"),
|
|
46
|
+
-(entry[1].dense_similarity or 0.0)))
|
|
47
|
+
hits = []
|
|
48
|
+
for distance, item in distances:
|
|
49
|
+
evidence = item.revision.evidence
|
|
50
|
+
score = 1 / (1 + distance.total_seconds() / 86400)
|
|
51
|
+
quality = (evidence.confidence + evidence.importance) / 2
|
|
52
|
+
hits.append(SearchHit(item.revision, score, item.lexical_rank, item.dense_similarity, score, quality))
|
|
53
|
+
return hits
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def rank(candidates: list[Candidate], strategy: str, reference: str, target: str | None) -> list[SearchHit]:
|
|
57
|
+
if strategy == "lexical":
|
|
58
|
+
candidates = [item for item in candidates if item.lexical_rank is not None]
|
|
59
|
+
if strategy == "dense":
|
|
60
|
+
candidates = [item for item in candidates if item.dense_similarity is not None]
|
|
61
|
+
|
|
62
|
+
anchor = datetime.fromisoformat(target or reference)
|
|
63
|
+
half_life = 180 if target else 365
|
|
64
|
+
weights = (0.45, 0.45, 0.10) if target else (0.70, 0.15, 0.15)
|
|
65
|
+
recency_order = sorted(candidates, key=lambda item: item.revision.evidence.id)
|
|
66
|
+
# The store normalizes timestamps to UTC text before creating candidates.
|
|
67
|
+
recency_order.sort(key=lambda item: str(item.revision.evidence.observed_at), reverse=True)
|
|
68
|
+
if strategy == "nearest":
|
|
69
|
+
return _nearest(recency_order, anchor)
|
|
70
|
+
hits = []
|
|
71
|
+
for recency_rank, item in enumerate(recency_order, 1):
|
|
72
|
+
evidence = item.revision.evidence
|
|
73
|
+
elapsed = (anchor - datetime.fromisoformat(str(evidence.observed_at))).total_seconds() / 86400
|
|
74
|
+
distance = abs(elapsed) if target else max(0.0, elapsed)
|
|
75
|
+
temporal = 2 ** (-distance / half_life)
|
|
76
|
+
quality = (evidence.confidence + evidence.importance) / 2
|
|
77
|
+
lexical = 1 / (1 + 0.1 * (item.lexical_rank - 1)) if item.lexical_rank is not None else 0.0
|
|
78
|
+
dense = item.dense_similarity if item.dense_similarity is not None else 0.0
|
|
79
|
+
match strategy:
|
|
80
|
+
case "lexical":
|
|
81
|
+
score = lexical
|
|
82
|
+
case "dense":
|
|
83
|
+
score = dense
|
|
84
|
+
case "recent":
|
|
85
|
+
score = 1 / recency_rank
|
|
86
|
+
case "rrf":
|
|
87
|
+
lexical_term = 1 / (60 + item.lexical_rank) if item.lexical_rank is not None else 0.0
|
|
88
|
+
score = lexical_term + 1 / (60 + recency_rank)
|
|
89
|
+
case "adaptive" | "no-time" | "no-quality":
|
|
90
|
+
relevance = max(lexical, dense)
|
|
91
|
+
base, time_weight, quality_weight = weights
|
|
92
|
+
if strategy == "no-time":
|
|
93
|
+
base, time_weight = base + time_weight, 0.0
|
|
94
|
+
if strategy == "no-quality":
|
|
95
|
+
base, quality_weight = base + quality_weight, 0.0
|
|
96
|
+
score = relevance * (base + time_weight * temporal + quality_weight * quality)
|
|
97
|
+
hits.append(SearchHit(item.revision, score, item.lexical_rank, item.dense_similarity, temporal, quality))
|
|
98
|
+
return sorted(hits, key=lambda hit: hit.score, reverse=True)
|