receiptdb 1.0.0rc1__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.
Files changed (101) hide show
  1. receiptdb/__init__.py +32 -0
  2. receiptdb/__main__.py +3 -0
  3. receiptdb/_version.py +1 -0
  4. receiptdb/answer_spans.py +584 -0
  5. receiptdb/answerdiff.py +106 -0
  6. receiptdb/apikeys.py +107 -0
  7. receiptdb/cache.py +58 -0
  8. receiptdb/chunking.py +27 -0
  9. receiptdb/cli.py +2478 -0
  10. receiptdb/client.py +361 -0
  11. receiptdb/completion.py +100 -0
  12. receiptdb/config.py +1907 -0
  13. receiptdb/dbwatch.py +257 -0
  14. receiptdb/denials.py +35 -0
  15. receiptdb/dsr.py +496 -0
  16. receiptdb/embedders.py +252 -0
  17. receiptdb/grounding.py +129 -0
  18. receiptdb/hashing.py +119 -0
  19. receiptdb/importers.py +1006 -0
  20. receiptdb/incarnation.py +465 -0
  21. receiptdb/ingest.py +490 -0
  22. receiptdb/integrations/__init__.py +0 -0
  23. receiptdb/integrations/_sources.py +141 -0
  24. receiptdb/integrations/anthropic.py +52 -0
  25. receiptdb/integrations/haystack.py +457 -0
  26. receiptdb/integrations/langchain.py +396 -0
  27. receiptdb/integrations/langgraph.py +517 -0
  28. receiptdb/integrations/llamaindex.py +444 -0
  29. receiptdb/integrations/semantic_kernel.py +382 -0
  30. receiptdb/labels.py +408 -0
  31. receiptdb/ledger.py +9665 -0
  32. receiptdb/llm.py +508 -0
  33. receiptdb/logs.py +284 -0
  34. receiptdb/mcp_server.py +247 -0
  35. receiptdb/memory.py +460 -0
  36. receiptdb/metrics.py +611 -0
  37. receiptdb/migrate.py +360 -0
  38. receiptdb/migrations/0002_upgrade_to_0_4.sql +49 -0
  39. receiptdb/migrations/0003_index_audit.sql +10 -0
  40. receiptdb/migrations/0004_keyset_paging.sql +13 -0
  41. receiptdb/migrations/0005_meta_index.sql +9 -0
  42. receiptdb/migrations/0006_partial_gin.sql +12 -0
  43. receiptdb/migrations/0007_halfvec.sql +24 -0
  44. receiptdb/migrations/0008_hot_status_updates.sql +35 -0
  45. receiptdb/migrations/0009_vector_retirement.sql +27 -0
  46. receiptdb/migrations/0010_held_records.sql +21 -0
  47. receiptdb/migrations/0011_key_destructions.sql +11 -0
  48. receiptdb/migrations/0012_feed_position.sql +31 -0
  49. receiptdb/migrations/0013_retention_requirements.sql +20 -0
  50. receiptdb/migrations/0014_webhook_dead_letters.sql +22 -0
  51. receiptdb/migrations/0015_dsr_request_index.sql +8 -0
  52. receiptdb/migrations/0016_scan_verdicts.sql +19 -0
  53. receiptdb/migrations/0017_unknown_provenance.sql +7 -0
  54. receiptdb/migrations/0018_email_subjects.sql +31 -0
  55. receiptdb/migrations/0019_events_by_user.sql +7 -0
  56. receiptdb/migrations/0020_dsr_requests.sql +17 -0
  57. receiptdb/migrations/0021_drop_feed_idx_again.sql +7 -0
  58. receiptdb/migrations/0022_pii_detection.sql +29 -0
  59. receiptdb/migrations/0023_proposed_candidates_idx.sql +6 -0
  60. receiptdb/migrations/0024_held_erasures_per_subject.sql +12 -0
  61. receiptdb/migrations/0025_scanner_holds_idx.sql +11 -0
  62. receiptdb/migrations/0026_acl_index_no_pending_list.sql +13 -0
  63. receiptdb/migrations/0027_acl_index_pending_list.sql +12 -0
  64. receiptdb/migrations/0028_erase_events_idx.sql +8 -0
  65. receiptdb/migrations/0029_erased_history_idx.sql +7 -0
  66. receiptdb/migrations/0030_source_version_tag.sql +9 -0
  67. receiptdb/migrations/0031_drop_key_destructions.sql +21 -0
  68. receiptdb/migrations/0032_incarnation.sql +43 -0
  69. receiptdb/migrations/0033_feed_fork.sql +223 -0
  70. receiptdb/migrations/0034_ledger_id.sql +8 -0
  71. receiptdb/migrations/0035_documents_created_id_idx.sql +9 -0
  72. receiptdb/migrations/0036_feed_start.sql +216 -0
  73. receiptdb/migrations/README.md +40 -0
  74. receiptdb/onetrust.py +589 -0
  75. receiptdb/openlineage.py +582 -0
  76. receiptdb/outbound.py +376 -0
  77. receiptdb/pii.py +503 -0
  78. receiptdb/pii_patterns.py +314 -0
  79. receiptdb/pinning.py +285 -0
  80. receiptdb/pooling.py +836 -0
  81. receiptdb/ratelimit.py +127 -0
  82. receiptdb/replay.py +676 -0
  83. receiptdb/replication.py +124 -0
  84. receiptdb/responses.py +350 -0
  85. receiptdb/retrying.py +26 -0
  86. receiptdb/scanners.py +663 -0
  87. receiptdb/schema.sql +206 -0
  88. receiptdb/server.py +4076 -0
  89. receiptdb/siem.py +424 -0
  90. receiptdb/stability.py +251 -0
  91. receiptdb/support.py +411 -0
  92. receiptdb/tracing.py +157 -0
  93. receiptdb/verify.py +707 -0
  94. receiptdb/webhooks.py +1108 -0
  95. receiptdb-1.0.0rc1.dist-info/METADATA +509 -0
  96. receiptdb-1.0.0rc1.dist-info/RECORD +101 -0
  97. receiptdb-1.0.0rc1.dist-info/WHEEL +5 -0
  98. receiptdb-1.0.0rc1.dist-info/entry_points.txt +2 -0
  99. receiptdb-1.0.0rc1.dist-info/licenses/LICENSE +105 -0
  100. receiptdb-1.0.0rc1.dist-info/licenses/NOTICE +16 -0
  101. receiptdb-1.0.0rc1.dist-info/top_level.txt +1 -0
receiptdb/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ from ._version import __version__
2
+ from .embedders import Embedder, HashEmbedder
3
+ from .labels import Labels, LabelError, combine, source_labels
4
+ from .ledger import (
5
+ ErasedSourceError,
6
+ ErasureCertificate,
7
+ Hit,
8
+ CascadeBusyError,
9
+ CascadeContentionError,
10
+ CascadeTimeoutError,
11
+ Impact,
12
+ InactiveRecordError,
13
+ KeyStoreBehindError,
14
+ KeyStoreUnavailableError,
15
+ Ledger,
16
+ ModelMismatchError,
17
+ NotFoundError,
18
+ Policy,
19
+ ReasonError,
20
+ ReceiptError,
21
+ RetractedSourceError,
22
+ SupersededSourceError,
23
+ TaintedInputError,
24
+ RecheckOverloadedError,
25
+ VectorsUnavailableError,
26
+ record_id,
27
+ )
28
+
29
+ __all__ = [
30
+ "__version__", "CascadeBusyError", "CascadeContentionError", "CascadeTimeoutError", "ErasedSourceError", "ErasureCertificate", "Embedder", "HashEmbedder", "Hit", "Impact", "InactiveRecordError", "KeyStoreBehindError", "KeyStoreUnavailableError", "LabelError", "Labels", "Ledger", "ModelMismatchError", "NotFoundError",
31
+ "Policy", "ReasonError", "ReceiptError", "RetractedSourceError", "SupersededSourceError", "TaintedInputError", "RecheckOverloadedError", "VectorsUnavailableError", "combine", "record_id", "source_labels",
32
+ ]
receiptdb/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
receiptdb/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0-rc.1"
@@ -0,0 +1,584 @@
1
+ """Answer receipts as OpenTelemetry spans, for LLM observability tools (roadmap M3-07): self-hosted Langfuse and Arize
2
+ Phoenix, from the default schema, by the deployment. ``pip install 'receiptdb[otel]'`` and
3
+
4
+ RECEIPTDB_LANGFUSE_URL=http://langfuse:3000 # Langfuse's base URL
5
+ RECEIPTDB_LANGFUSE_PUBLIC_KEY=pk-lf-... # a project's API keys
6
+ RECEIPTDB_LANGFUSE_SECRET_KEY=sk-lf-...
7
+ RECEIPTDB_PHOENIX_URL=http://phoenix:6006 # Phoenix's base URL
8
+ RECEIPTDB_PHOENIX_API_KEY=... # optional: with Phoenix's authentication on
9
+ RECEIPTDB_PHOENIX_PROJECT=receiptdb # the Phoenix project (default receiptdb)
10
+ RECEIPTDB_ANSWER_SPANS_CONTENT=unrestricted # unrestricted (default), all, or off
11
+ RECEIPTDB_ANSWER_SPANS_ERASE=on # delete an erased answer's trace (default on)
12
+ RECEIPTDB_ANSWER_SPANS_FROM=start # optional: also the answers recorded before (default: from now)
13
+
14
+ Each answer recorded in the default schema (`Ledger.record_answer`: the API, `receipt ask`, the MCP server, the
15
+ integrations) is one trace of two spans, sent as OTLP over HTTP in protobuf (the one encoding both accept):
16
+
17
+ - `receiptdb.answer`, the root (OpenInference CHAIN, Langfuse `chain`): the answer's ID, transform, destination, the
18
+ grounding verdict, and, when its labels allow (below), the question as `input.value`, the answer as `output.value`
19
+ and the asker as `user.id`;
20
+ - `receiptdb.retrieval`, its child (RETRIEVER, `retriever`): the records the answer was built from, as OpenInference's
21
+ documents (`retrieval.documents.<i>.document.id` and their kind), never their content.
22
+
23
+ The trace ID is the first 32 hex characters of the answer's ID, and the spans' IDs the next 16 and the 16 after: an
24
+ answer is found by its ID in either tool, a re-sent batch writes the same spans, and an erasure knows which trace to
25
+ delete without a stored mapping. Both spans are at `answered_at`, with no duration (the receipt records when, not how
26
+ long).
27
+
28
+ Content. `unrestricted` (the default) sends the question, the answer and the asker only for an active answer anyone
29
+ may read (no readers clause) whose egress labels allow the sink as a destination (`langfuse`, `phoenix`: label
30
+ documents `--egress local,langfuse` to allow it); `all` drops the readers condition; `off` sends no text (the IDs and
31
+ the receipt's own facts: transform, destination, the grounding verdict). Egress labels always apply: they are the rule
32
+ for what leaves.
33
+
34
+ A receipt a library caller wrote by hand (`derive_many` with kind `answer`, as the API's routes never allow) may carry
35
+ metadata in another shape: the spans take what fits and fall back for the rest (`created_at` for an unreadable
36
+ `answered_at`), since a round that raised would be retried as an outage for good, with every later answer behind it
37
+ (review AK-1).
38
+
39
+ Erasure (RECEIPTDB_ANSWER_SPANS_ERASE, on by default): an `erase` event deletes the traces of the answers it erased
40
+ (Langfuse: `DELETE /api/public/traces`, at most 1,000 IDs a call, deleted asynchronously by its worker; Phoenix:
41
+ `DELETE /v1/traces/<trace ID>`, a 404 being nothing to delete).
42
+
43
+ A deletion the tool refuses as content (a key without the right, say) is an erasure not applied there: the erase
44
+ event is dead-lettered on its own, `/v1/status` counts it (`erasures_refused`), as does
45
+ `receiptdb_answer_spans_erasures_refused`, and `receipt verify-erasure` reports it against the certificate, whose
46
+ scope names the tools that delete traces after the commit (`traces`, "pending"). A tool that is down is retried
47
+ forever (AY-10); so is a key without the right to delete (403), but a streak of 401, 403, 404 or 410 counts the erase
48
+ events behind it as refused too, and `verify-erasure` reports it as a problem (BK-1).
49
+
50
+ Each sink is a webhook round (ADR-0028 point 7), like the SIEM sinks: the same lock, cursor (`spans:<sink>`), backoff,
51
+ bisection and dead letters, so delivery is at least once, in feed order, and an answer erased before its round reads
52
+ it is never sent.
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import base64
58
+ import json
59
+ import logging
60
+ from dataclasses import dataclass, field
61
+ from datetime import datetime, timedelta, timezone
62
+ from typing import Callable
63
+ from urllib.parse import quote, urlsplit
64
+
65
+ from psycopg import sql
66
+
67
+ from . import _version, config, migrate
68
+ from .labels import may_send
69
+ from .ledger import SEALED_META_KEYS, Ledger, plural
70
+ from .webhooks import HTTP_TIMEOUT, Target, Webhook, public_url, start_cursor
71
+
72
+ try:
73
+ from . import metrics as _metrics
74
+ except ImportError: # prometheus_client not installed
75
+ _metrics = None
76
+
77
+ log = logging.getLogger("receiptdb.answer_spans")
78
+ SINKS = ("langfuse", "phoenix")
79
+ OPS = ("derive", "derive_batch", "erase")
80
+ CONTENT = ("unrestricted", "all", "off")
81
+ ERASE_LISTED = 1000 # answers an erase event lists (Ledger._erase_log); a list that long may be cut short
82
+ LANGFUSE_DELETE_BATCH = 1000 # the most trace IDs Langfuse's DELETE /api/public/traces takes
83
+
84
+
85
+ def cursor_key(sink: str) -> str:
86
+ """A sink's cursor key in the schema's `settings` (its state is `<key>:state`, the dead letters' `cursor_key`)."""
87
+ return f"spans:{sink}"
88
+
89
+
90
+ def trace_ids(answer_id: str) -> tuple[str, str, str]:
91
+ """An answer's trace ID and its two spans' IDs (hex), from its ID: a SHA-256 in hex, 64 characters."""
92
+ return answer_id[:32], answer_id[32:48], answer_id[48:64]
93
+
94
+
95
+ # ------------------------------------------------------------------------------------------ the spans
96
+
97
+ @dataclass
98
+ class Answer:
99
+ """An answer as the spans carry it, read from the ledger (`read_answers`)."""
100
+ id: str
101
+ at: datetime # answered_at (aware)
102
+ transform: str
103
+ inputs: list[tuple[str, str]] # (record ID, kind)
104
+ meta: dict
105
+ status: str
106
+ unrestricted: bool # no readers clause
107
+ egress: list
108
+ unopened: bool = False # its sealed question or answer can't be opened now (M5-53)
109
+
110
+
111
+ def read_answers(led: Ledger, ids: list[str]) -> list[Answer]:
112
+ """The answers among `ids` that a sink still sends: not erased, not held for an erasure. Sealed content is opened
113
+ with the ledger's codec, when it has one; a sealed question or answer that can't be opened (a key not in the key
114
+ store, a value that doesn't decrypt) is left out of `meta`, the answer marked `unopened`, never the marker in its
115
+ place (M5-53)."""
116
+ if not ids:
117
+ return []
118
+ rows = led.conn.execute(
119
+ """SELECT id, status, meta, acl, egress, transform, created_at FROM records
120
+ WHERE id = ANY(%s) AND kind = 'answer' AND status NOT IN ('erased', 'held')""", (list(ids),)).fetchall()
121
+ if not rows:
122
+ return []
123
+ inputs: dict[str, list] = {}
124
+ for e in led.conn.execute("""SELECT e.child, e.parent, r.kind FROM edges e JOIN records r ON r.id = e.parent
125
+ WHERE e.child = ANY(%s) ORDER BY e.child, e.parent""", ([r["id"] for r in rows],)):
126
+ inputs.setdefault(e["child"], []).append((e["parent"], e["kind"]))
127
+ order = {rid: i for i, rid in enumerate(ids)}
128
+ out = []
129
+ for r in sorted(rows, key=lambda r: order[r["id"]]):
130
+ stored = r["meta"] if isinstance(r["meta"], dict) else {}
131
+ r = led._open_row(r)
132
+ meta = r["meta"] if isinstance(r["meta"], dict) else {}
133
+ unopened = [k for k in SEALED_META_KEYS if led._unopened(stored.get(k), meta.get(k))]
134
+ meta = {k: v for k, v in meta.items() if k not in unopened}
135
+ out.append(Answer(r["id"], answered_at(meta, r["created_at"]), r["transform"],
136
+ inputs.get(r["id"], []), meta, r["status"], not r["acl"], r["egress"] or [],
137
+ unopened=bool(unopened)))
138
+ return out
139
+
140
+
141
+ def answered_at(meta: dict, created_at: datetime) -> datetime:
142
+ """When the answer was given: `meta.answered_at` (`record_answer` writes the database's clock there), or the
143
+ record's `created_at` when a library caller wrote something else, so that a receipt is always sent (AK-1)."""
144
+ v = meta.get("answered_at")
145
+ if isinstance(v, str):
146
+ try:
147
+ at = datetime.fromisoformat(v)
148
+ except ValueError:
149
+ return created_at
150
+ return at if at.tzinfo is not None else at.replace(tzinfo=timezone.utc)
151
+ return created_at
152
+
153
+
154
+ def shows_content(a: Answer, sink: str, content: str) -> bool:
155
+ """Whether the spans carry the answer's question, text and asker (the module's "Content")."""
156
+ if content == "off" or a.status != "active" or a.unopened: # no content to carry: never the marker as it (M5-53)
157
+ return False
158
+ if not may_send(tuple(tuple(c) for c in a.egress), sink):
159
+ return False
160
+ return content == "all" or a.unrestricted
161
+
162
+
163
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
164
+
165
+
166
+ def nanos(at: datetime) -> int:
167
+ """An aware datetime as OTLP's Unix nanoseconds, exact to the microsecond the database keeps."""
168
+ return (at - _EPOCH) // timedelta(microseconds=1) * 1000
169
+
170
+
171
+ def _value(v):
172
+ from opentelemetry.proto.common.v1.common_pb2 import AnyValue, ArrayValue
173
+ if isinstance(v, bool):
174
+ return AnyValue(bool_value=v)
175
+ if isinstance(v, int):
176
+ return AnyValue(int_value=v)
177
+ if isinstance(v, float):
178
+ return AnyValue(double_value=v)
179
+ if isinstance(v, (list, tuple)):
180
+ return AnyValue(array_value=ArrayValue(values=[_value(x) for x in v]))
181
+ if isinstance(v, dict):
182
+ return AnyValue(string_value=json.dumps(v, default=str))
183
+ return AnyValue(string_value=str(v))
184
+
185
+
186
+ def _attrs(d: dict) -> list:
187
+ from opentelemetry.proto.common.v1.common_pb2 import KeyValue
188
+ return [KeyValue(key=k, value=_value(v)) for k, v in d.items() if v is not None]
189
+
190
+
191
+ def span_attributes(a: Answer, with_content: bool) -> tuple[dict, dict]:
192
+ """The two spans' attributes: OpenInference's names (Phoenix reads them; Langfuse maps the span kind and input and
193
+ output from them) and Langfuse's own observation type, with `receiptdb.*` for what neither names."""
194
+ grounding = a.meta.get("grounding")
195
+ violation = a.meta.get("egress_violation")
196
+ root = {"openinference.span.kind": "CHAIN", "langfuse.observation.type": "chain",
197
+ "langfuse.trace.name": "receiptdb.answer",
198
+ "receiptdb.answer.id": a.id, "receiptdb.transform": a.transform,
199
+ "receiptdb.destination": a.meta.get("destination"),
200
+ "receiptdb.inputs": [rid for rid, _ in a.inputs],
201
+ "receiptdb.content": with_content}
202
+ if isinstance(grounding, dict) and grounding: # `Ledger.store_grounding` writes a dict; a hand-written one may not
203
+ root.update({"receiptdb.grounding.score": grounding.get("score"),
204
+ "receiptdb.grounding.grounded": grounding.get("grounded"),
205
+ "receiptdb.grounding.method": grounding.get("method")})
206
+ if isinstance(violation, list) and violation:
207
+ root["receiptdb.egress_violation"] = [str(v) for v in violation]
208
+ retrieval = {"openinference.span.kind": "RETRIEVER", "langfuse.observation.type": "retriever",
209
+ "receiptdb.answer.id": a.id, "receiptdb.inputs": [rid for rid, _ in a.inputs]}
210
+ for i, (rid, kind) in enumerate(a.inputs):
211
+ retrieval[f"retrieval.documents.{i}.document.id"] = rid
212
+ retrieval[f"retrieval.documents.{i}.document.metadata"] = json.dumps({"kind": kind})
213
+ if with_content:
214
+ question = _text(a.meta.get("question"))
215
+ root.update({"input.value": question, "input.mime_type": "text/plain",
216
+ "output.value": _text(a.meta.get("answer")), "output.mime_type": "text/plain",
217
+ "user.id": _text(a.meta.get("asked_by"))})
218
+ retrieval.update({"input.value": question, "input.mime_type": "text/plain"})
219
+ return root, retrieval
220
+
221
+
222
+ def _text(v) -> str | None:
223
+ """A text attribute (OpenInference's `input.value`, `user.id`): the string, or JSON for a hand-written other shape."""
224
+ return v if v is None or isinstance(v, str) else json.dumps(v, default=str)
225
+
226
+
227
+ def export_request(answers: list[Answer], sink: str, content: str, resource: dict | None = None) -> bytes:
228
+ """An OTLP ExportTraceServiceRequest, serialized: the two spans of each answer."""
229
+ from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
230
+ from opentelemetry.proto.common.v1.common_pb2 import InstrumentationScope
231
+ from opentelemetry.proto.resource.v1.resource_pb2 import Resource
232
+ from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpans, ScopeSpans, Span, Status
233
+ spans = []
234
+ for a in answers:
235
+ trace_id, root_id, retrieval_id = (bytes.fromhex(x) for x in trace_ids(a.id))
236
+ at = nanos(a.at)
237
+ root, retrieval = span_attributes(a, shows_content(a, sink, content))
238
+ ok = Status(code=Status.STATUS_CODE_OK)
239
+ spans.append(Span(trace_id=trace_id, span_id=root_id, name="receiptdb.answer", kind=Span.SPAN_KIND_INTERNAL,
240
+ start_time_unix_nano=at, end_time_unix_nano=at, attributes=_attrs(root), status=ok))
241
+ spans.append(Span(trace_id=trace_id, span_id=retrieval_id, parent_span_id=root_id, name="receiptdb.retrieval",
242
+ kind=Span.SPAN_KIND_INTERNAL, start_time_unix_nano=at, end_time_unix_nano=at,
243
+ attributes=_attrs(retrieval), status=ok))
244
+ res = Resource(attributes=_attrs({"service.name": "receiptdb", "service.version": _version.__version__,
245
+ **(resource or {})}))
246
+ scope = InstrumentationScope(name="receiptdb.answer_spans", version=_version.__version__)
247
+ return ExportTraceServiceRequest(resource_spans=[ResourceSpans(
248
+ resource=res, scope_spans=[ScopeSpans(scope=scope, spans=spans)])]).SerializeToString()
249
+
250
+
251
+ # ------------------------------------------------------------------------------------------ the sinks
252
+
253
+ def _first_line(text: str) -> str:
254
+ return (text.strip().splitlines() or [""])[0][:200]
255
+
256
+
257
+ @dataclass
258
+ class Sink:
259
+ """One tool. `export(answers)` and `delete(trace IDs)` return (status, the answer's first line) as a webhook
260
+ sender does, and raise when no answer came."""
261
+ name: str
262
+ url: str
263
+ content: str = "unrestricted"
264
+ erase: bool = True
265
+ http: object = field(default=None, repr=False)
266
+
267
+ @property
268
+ def cursor_key(self) -> str:
269
+ return cursor_key(self.name)
270
+
271
+ def _client(self):
272
+ if self.http is None:
273
+ import httpx # the server extra's, imported when a sink is made
274
+ self.http = httpx.Client(timeout=HTTP_TIMEOUT, follow_redirects=False)
275
+ return self.http
276
+
277
+ def observe(self, tenant: str, outcome: str, n: int = 1) -> None:
278
+ if _metrics is not None:
279
+ _metrics.observe_answer_spans(self.name, outcome, n)
280
+
281
+ def headers(self) -> dict:
282
+ return {}
283
+
284
+ @property
285
+ def traces_url(self) -> str:
286
+ raise NotImplementedError
287
+
288
+ def export(self, answers: list[Answer]) -> tuple[int, str]:
289
+ from .outbound import call # the answer's first 64 KiB at most, within a deadline (GB-16)
290
+ r = call(self._client(), "POST", self.traces_url, truncate=True,
291
+ content=export_request(answers, self.name, self.content, self.resource()),
292
+ headers={**self.headers(), "content-type": "application/x-protobuf"})
293
+ if 200 <= r.status_code < 300: # a partial success is a success: the tool says what it dropped (as the SIEM's OTLP)
294
+ rejected, why = _partial_success(r)
295
+ if rejected:
296
+ log.warning("%s dropped %s of %d spans: %s", self.name, rejected, 2 * len(answers), why)
297
+ return r.status_code, _first_line(r.text or "")
298
+
299
+ def resource(self) -> dict:
300
+ return {}
301
+
302
+ def delete(self, traces: list[str]) -> tuple[int, str]:
303
+ raise NotImplementedError
304
+
305
+
306
+ @dataclass
307
+ class LangfuseSink(Sink):
308
+ """Langfuse (v4): OTLP at `/api/public/otel/v1/traces` with the project's keys as Basic auth and
309
+ `x-langfuse-ingestion-version: 4` (ingested directly, not through the dual-write pipeline, which shows a trace
310
+ minutes later); traces deleted by `DELETE /api/public/traces`, which answers 200 for an unknown ID too."""
311
+ public_key: str = ""
312
+ secret_key: str = field(default="", repr=False)
313
+
314
+ @property
315
+ def base(self) -> str:
316
+ return self.url.rstrip("/")
317
+
318
+ @property
319
+ def traces_url(self) -> str:
320
+ return self.base + "/api/public/otel/v1/traces"
321
+
322
+ def headers(self) -> dict:
323
+ token = base64.b64encode(f"{self.public_key}:{self.secret_key}".encode()).decode()
324
+ return {"authorization": f"Basic {token}", "x-langfuse-ingestion-version": "4"}
325
+
326
+ def delete(self, traces: list[str]) -> tuple[int, str]:
327
+ for i in range(0, len(traces), LANGFUSE_DELETE_BATCH):
328
+ from .outbound import call # GB-16
329
+ r = call(self._client(), "DELETE", self.base + "/api/public/traces", truncate=True,
330
+ content=json.dumps({"traceIds": traces[i:i + LANGFUSE_DELETE_BATCH]}),
331
+ headers={**self.headers(), "content-type": "application/json"})
332
+ if not 200 <= r.status_code < 300:
333
+ return r.status_code, _first_line(r.text or "")
334
+ return 200, ""
335
+
336
+
337
+ @dataclass
338
+ class PhoenixSink(Sink):
339
+ """Arize Phoenix: OTLP at `/v1/traces` (protobuf only), the project named by `x-project-name` and the resource's
340
+ `openinference.project.name`, a bearer API key when its authentication is on; a trace deleted by
341
+ `DELETE /v1/traces/<OpenTelemetry trace ID>`, 404 when Phoenix holds none."""
342
+ api_key: str | None = field(default=None, repr=False)
343
+ project: str = "receiptdb"
344
+
345
+ @property
346
+ def base(self) -> str:
347
+ return self.url.rstrip("/")
348
+
349
+ @property
350
+ def traces_url(self) -> str:
351
+ return self.base + "/v1/traces"
352
+
353
+ def headers(self) -> dict:
354
+ h = {"x-project-name": self.project}
355
+ if self.api_key:
356
+ h["authorization"] = f"Bearer {self.api_key}"
357
+ return h
358
+
359
+ def resource(self) -> dict:
360
+ return {"openinference.project.name": self.project}
361
+
362
+ def delete(self, traces: list[str]) -> tuple[int, str]:
363
+ for t in traces:
364
+ from .outbound import call # GB-16
365
+ r = call(self._client(), "DELETE", f"{self.base}/v1/traces/{quote(t)}", truncate=True,
366
+ headers=self.headers())
367
+ if r.status_code != 404 and not 200 <= r.status_code < 300: # 404: nothing there to delete
368
+ return r.status_code, _first_line(r.text or "")
369
+ return 200, ""
370
+
371
+
372
+ def _partial_success(r) -> tuple[int, str]:
373
+ """What an OTLP success says it rejected: the ExportTraceServiceResponse as protobuf (Phoenix answers in the
374
+ request's encoding) or as JSON (`partialSuccess.rejectedSpans`); (0, "") for a body that is neither."""
375
+ try:
376
+ if "protobuf" in (r.headers.get("content-type") or ""):
377
+ from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceResponse
378
+ p = ExportTraceServiceResponse.FromString(r.content).partial_success
379
+ return int(p.rejected_spans), p.error_message
380
+ partial = ((r.json() or {}).get("partialSuccess") or {}) if r.content else {}
381
+ return int(partial.get("rejectedSpans") or 0), str(partial.get("errorMessage") or "")
382
+ except Exception: # noqa: BLE001 - not the OTLP response: nothing to report
383
+ return 0, ""
384
+
385
+
386
+ def config_errors(v: dict) -> list[str]:
387
+ """What `receipt config check` says about these settings (`v`: the parsed environment)."""
388
+ errors = []
389
+ for name in ("RECEIPTDB_LANGFUSE_URL", "RECEIPTDB_PHOENIX_URL"):
390
+ url = v.get(name)
391
+ if url:
392
+ u = urlsplit(url)
393
+ if u.scheme not in ("http", "https") or not u.hostname:
394
+ errors.append(f"{name}: http:// or https:// and a host, not {public_url(url)!r}")
395
+ if v.get("RECEIPTDB_LANGFUSE_URL") and not (v.get("RECEIPTDB_LANGFUSE_PUBLIC_KEY") and v.get("RECEIPTDB_LANGFUSE_SECRET_KEY")):
396
+ errors.append("RECEIPTDB_LANGFUSE_URL needs RECEIPTDB_LANGFUSE_PUBLIC_KEY and _SECRET_KEY: a project's API keys")
397
+ return errors
398
+
399
+
400
+ def sinks_from_env() -> list[Sink]:
401
+ """The sinks the environment configures; ValueError for a combination that doesn't work (the server doesn't
402
+ start), and RuntimeError without the OpenTelemetry packages."""
403
+ names = ("RECEIPTDB_LANGFUSE_URL", "RECEIPTDB_LANGFUSE_PUBLIC_KEY", "RECEIPTDB_LANGFUSE_SECRET_KEY",
404
+ "RECEIPTDB_PHOENIX_URL")
405
+ v = {n: config.get(n) for n in names}
406
+ errors = config_errors(v)
407
+ if errors:
408
+ raise ValueError("; ".join(errors))
409
+ common = {"content": config.get("RECEIPTDB_ANSWER_SPANS_CONTENT"), "erase": config.get("RECEIPTDB_ANSWER_SPANS_ERASE")}
410
+ sinks: list[Sink] = []
411
+ if v["RECEIPTDB_LANGFUSE_URL"]:
412
+ sinks.append(LangfuseSink("langfuse", v["RECEIPTDB_LANGFUSE_URL"], public_key=v["RECEIPTDB_LANGFUSE_PUBLIC_KEY"],
413
+ secret_key=v["RECEIPTDB_LANGFUSE_SECRET_KEY"], **common))
414
+ if v["RECEIPTDB_PHOENIX_URL"]:
415
+ sinks.append(PhoenixSink("phoenix", v["RECEIPTDB_PHOENIX_URL"], api_key=config.get("RECEIPTDB_PHOENIX_API_KEY"),
416
+ project=config.get("RECEIPTDB_PHOENIX_PROJECT"), **common))
417
+ if sinks:
418
+ try:
419
+ import opentelemetry.proto.collector.trace.v1.trace_service_pb2 # noqa: F401
420
+ except ImportError as e:
421
+ raise RuntimeError("exporting answers as spans needs the OpenTelemetry packages: "
422
+ "pip install 'receiptdb[otel]'") from e
423
+ return sinks
424
+
425
+
426
+ # ------------------------------------------------------------------------------------------ the round's sender
427
+
428
+ def concerns(event: dict) -> bool:
429
+ """Whether a feed event is one a sink's round makes a request for: a `derive` of an answer, a `derive_batch` with
430
+ answers among its kinds, an `erase` listing answers. The round passes the others (chunks, relabels, the rest of
431
+ the log) without a request, so they are never the evidence that a refused answer was refused for its content
432
+ (`Target.filter`, review AK-2)."""
433
+ d = event.get("detail") or {}
434
+ if event["op"] == "derive":
435
+ return d.get("kind") == "answer" and bool(event.get("record_id"))
436
+ if event["op"] == "derive_batch":
437
+ return bool((d.get("kinds") or {}).get("answer"))
438
+ return event["op"] == "erase" and bool(d.get("answers"))
439
+
440
+
441
+ def answers_of(led: Ledger, events: list[dict]) -> list[str]:
442
+ """The answers the `derive` and `derive_batch` events among `events` recorded, in feed order."""
443
+ ids: list[str] = []
444
+ batches: list[str] = []
445
+ for e in events:
446
+ d = e.get("detail") or {}
447
+ if e["op"] == "derive" and d.get("kind") == "answer" and e.get("record_id"):
448
+ ids.append(e["record_id"])
449
+ elif e["op"] == "derive_batch" and (d.get("kinds") or {}).get("answer"):
450
+ batches += [r for r in d.get("records") or [] if isinstance(r, str)]
451
+ if batches:
452
+ found = {r["id"] for r in led.conn.execute("SELECT id FROM records WHERE id = ANY(%s) AND kind = 'answer'",
453
+ (batches,))}
454
+ ids += [r for r in batches if r in found]
455
+ return ids
456
+
457
+
458
+ def erased_answers(led: Ledger, events: list[dict]) -> list[str]:
459
+ """The answers the `erase` events among `events` erased. The event lists at most ERASE_LISTED; a list that long is
460
+ completed from the records: those erased in the same transaction carry the event's time as their status change
461
+ (both are its `now()`)."""
462
+ ids: list[str] = []
463
+ for e in events:
464
+ if e["op"] != "erase":
465
+ continue
466
+ listed = [a for a in (e.get("detail") or {}).get("answers") or [] if isinstance(a, str)]
467
+ if len(listed) >= ERASE_LISTED:
468
+ listed = [r["id"] for r in led.conn.execute(
469
+ """SELECT id FROM records WHERE kind = 'answer' AND status = 'erased' AND status_changed_at = %s::timestamptz
470
+ ORDER BY id""", (e["at"],))] or listed
471
+ ids += listed
472
+ return ids
473
+
474
+
475
+ def send(sink: Sink, led: Ledger, events: list[dict]) -> tuple[int, str]:
476
+ """A batch of the feed to `sink`: the answers it recorded exported, the traces of those it erased deleted (an
477
+ answer both recorded and erased in the batch is read as erased: not sent, its trace deleted)."""
478
+ answers = read_answers(led, answers_of(led, events))
479
+ if answers:
480
+ status, text = sink.export(answers)
481
+ if not 200 <= status < 300:
482
+ return status, text
483
+ if sink.erase:
484
+ erased = list(dict.fromkeys(trace_ids(a)[0] for a in erased_answers(led, events)))
485
+ if erased:
486
+ status, text = sink.delete(erased)
487
+ if not 200 <= status < 300: # bisected down to the erase event alone, then retried and dead-lettered
488
+ log.warning("%s refused deleting the traces of %s (HTTP %s): the erasure isn't applied "
489
+ "there until it accepts; `receipt verify-erasure` and /v1/status say so", sink.name,
490
+ plural(len(erased), "erased answer"), status)
491
+ return status, text
492
+ return 200, ""
493
+
494
+
495
+ # ------------------------------------------------------------------------------------------ the rounds
496
+
497
+ class Source:
498
+ """The webhook scheduler's source of answer-span rounds: one per sink, in the default schema. A sink's cursor is
499
+ written at its first round: at `started`'s feed position (the server's start, before it served: an answer recorded
500
+ before the first round is still sent, G-38), the feed's end without it, or its start with
501
+ RECEIPTDB_ANSWER_SPANS_FROM=start. A cursor once written is kept: a sink removed and added again resumes where it
502
+ stopped. `setup(ledger)` gives the round's ledger what a request's has (Enterprise: the codec that opens sealed
503
+ questions and answers)."""
504
+
505
+ def __init__(self, sinks: list[Sink], schema: str, setup: Callable | None = None, from_start: bool = False,
506
+ batch: int = 100, started: tuple[str, int] | None = None):
507
+ self.sinks, self.schema, self.setup = sinks, schema, setup
508
+ self.from_start, self.batch, self.started = from_start, batch, started
509
+ self._ready: set[str] = set()
510
+
511
+ @classmethod
512
+ def from_env(cls, sinks: list[Sink], schema: str, setup: Callable | None = None,
513
+ started: tuple[str, int] | None = None) -> "Source":
514
+ return cls(sinks, schema, setup, config.get("RECEIPTDB_ANSWER_SPANS_FROM") == "start", started=started)
515
+
516
+ def target(self, sink: Sink) -> Target:
517
+ return Target(sink.url, (), OPS if sink.erase else OPS[:2], filter=concerns)
518
+
519
+ def __call__(self, connect) -> list[Webhook]:
520
+ conn = connect()
521
+ hooks = []
522
+ for sink in self.sinks:
523
+ if sink.name not in self._ready and self._prepare(conn, sink):
524
+ self._ready.add(sink.name)
525
+ if sink.name in self._ready:
526
+ hooks.append(self.hook(sink))
527
+ return hooks
528
+
529
+ def hook(self, sink: Sink) -> Webhook:
530
+ hook = Webhook(self.schema, self.target(sink), cursor_key=sink.cursor_key, sender=lambda *a: None,
531
+ batch=self.batch, kind=f"answer-span sink {sink.name}", observe=sink.observe,
532
+ dead_letters_hint=f"receipt webhook dead-letters --sink {sink.name}")
533
+
534
+ def sender(target, events, msg_id):
535
+ led = hook.ledger
536
+ if self.setup is not None:
537
+ self.setup(led)
538
+ return send(sink, led, events)
539
+ hook.send = sender
540
+ return hook
541
+
542
+ def _prepare(self, conn, sink: Sink) -> bool:
543
+ conn.execute(sql.SQL("SET search_path TO {}, public").format(sql.Identifier(self.schema)))
544
+ found = migrate.recorded(conn, "core")
545
+ if found is None or found[0] < migrate.latest_version():
546
+ return False
547
+ start_cursor(Ledger(conn, self.schema), from_start=self.from_start, cursor_key=sink.cursor_key,
548
+ after=self.started[1] if self.started else None)
549
+ # Whether this sink deletes erased answers' traces: an erasure's certificate names the tools that will (AY-10).
550
+ conn.execute("""INSERT INTO settings (key, value) VALUES (%s, %s)
551
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value""",
552
+ (f"{sink.cursor_key}:erase", "on" if sink.erase else "off"))
553
+ return True
554
+
555
+
556
+ def status(led: Ledger, sinks: list[Sink]) -> dict:
557
+ """Each sink's state, as `/v1/status` shows it to the deployment (webhooks.status), with `erasures_refused`: the
558
+ erase events whose traces are still in the tool because it refused them (AY-10, BK-1)."""
559
+ from .webhooks import status as round_status
560
+ return {s.name: {**round_status(led, Source([s], led.schema()).target(s), s.cursor_key),
561
+ "erasures_refused": erasures_refused(led, s.cursor_key)} for s in sinks}
562
+
563
+
564
+ def erasures_refused(led: Ledger, cursor_key: str, mapped: bool = True) -> int:
565
+ """The erase events a sink refused: as content (a pending refusal or a dead letter), or behind a failure streak that
566
+ says its credentials or URL are wrong (a key without the right to delete gets 403, retried as an outage, so every
567
+ erase event after the cursor waits for the fix, BK-1). Erasures not applied at the tool."""
568
+ from .webhooks import misconfigured_streak
569
+ if led.conn.execute("SELECT to_regclass('webhook_dead_letters') AS t").fetchone()["t"] is None:
570
+ return 0
571
+ refused = led.conn.execute("""SELECT count(*) AS n FROM webhook_dead_letters d JOIN events e ON e.id = d.event_id
572
+ WHERE d.cursor_key = %s AND e.op = 'erase'""", (cursor_key,)).fetchone()["n"]
573
+ # A sink that doesn't delete traces holds no erasure to apply, however its exports fail (BK-7).
574
+ erases = led.conn.execute("SELECT value FROM settings WHERE key = %s", (f"{cursor_key}:erase",)).fetchone()
575
+ if erases is None or erases["value"] != "on" or misconfigured_streak(led.conn, cursor_key) is None:
576
+ return refused
577
+ cursor = led.conn.execute("SELECT value FROM settings WHERE key = %s", (cursor_key,)).fetchone()
578
+ # through the feed's forks where the schema has them (0033; `mapped` False: a schema the conversion hasn't reached)
579
+ position = led._feed_position(int(cursor["value"]), mapped) if cursor is not None else 0
580
+ behind, _ = led._behind_feed( # on the feed's two indexes, as every scrape's backlog is (BK-8, AF-1)
581
+ position, "op = 'erase' AND jsonb_typeof(detail->'answers') = 'array' AND jsonb_array_length(detail->'answers') > 0"
582
+ " AND NOT EXISTS (SELECT 1 FROM webhook_dead_letters d WHERE d.cursor_key = %(k)s AND d.event_id = events.id)",
583
+ {"k": cursor_key})
584
+ return refused + behind