-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingestion_api.py
More file actions
1773 lines (1567 loc) · 68.1 KB
/
Copy pathingestion_api.py
File metadata and controls
1773 lines (1567 loc) · 68.1 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Ingestion API – FastAPI Wrapper
================================
HTTP interface for the ingestion pipeline.
Called by the MCP server via the Docker network.
Endpoints:
POST /scan — Scan text for PII (without ingestion)
POST /pseudonymize — Pseudonymize text without storage (chat path)
POST /ingest — Ingest text (full privacy pipeline)
POST /ingest/chunks — Ingest pre-processed chunks (adapter, ingest_text_chunks pipeline)
POST /snapshots/create — Create a knowledge snapshot
POST /sync — Sync all configured Git repositories
POST /sync/{repo_name} — Sync a single Git repository
GET /health — Health check
"""
import os
import json
import logging
import uuid
import time
import asyncio
import base64
import binascii
from datetime import datetime, timedelta, timezone
from typing import Any
import secrets
import httpx
import asyncpg
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from qdrant_client import AsyncQdrantClient
from qdrant_client.models import PointStruct
from prometheus_client import Counter, Histogram, make_asgi_app as prom_make_asgi_app
from pii_scanner import get_scanner
from snapshot_service import create_snapshot
from content_extraction import (
ContentExtractor,
detect_content_type,
mime_type_to_extension,
should_skip_file,
)
# ── Configuration ────────────────────────────────────────────
QDRANT_URL = os.getenv("QDRANT_URL", "http://qdrant:6333")
OPA_URL = os.getenv("OPA_URL", "http://opa:8181")
RERANKER_URL = os.getenv("RERANKER_URL", "http://reranker:8082")
# ── Backward-compat fallback ──
_OLLAMA_URL = os.getenv("OLLAMA_URL", "http://ollama:11434")
# ── Embedding provider ──
EMBEDDING_PROVIDER_URL = os.getenv("EMBEDDING_PROVIDER_URL", _OLLAMA_URL)
EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "nomic-embed-text")
EMBEDDING_API_KEY = os.getenv("EMBEDDING_API_KEY", "")
import sys as _sys
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from shared.llm_provider import EmbeddingProvider, CompletionProvider
from shared.config import build_postgres_url, read_secret, PG_POOL_MIN, PG_POOL_MAX
from shared.telemetry import (
init_telemetry, setup_auto_instrumentation, trace_operation,
request_telemetry_context, get_current_telemetry,
MetricsAggregator, TELEMETRY_IN_RESPONSE,
)
from shared.pii_verify_provider import (
create_pii_verify_provider,
build_candidates_from_locations,
apply_verdicts_to_scan_result,
VerifyStats,
)
from shared.opa_client import (
OpaPolicyMissingError,
opa_query,
verify_required_policies,
)
from shared.ingestion_auth import verify_ingestion_auth_configured
POSTGRES_URL = build_postgres_url()
embedding_provider = EmbeddingProvider(
base_url=EMBEDDING_PROVIDER_URL, api_key=EMBEDDING_API_KEY
)
from shared.embedding_cache import EmbeddingCache
embedding_cache = EmbeddingCache()
# ── LLM / Layer generation provider ──
LLM_PROVIDER_URL = os.getenv("LLM_PROVIDER_URL", os.getenv("OLLAMA_URL", "http://pb-ollama:11434"))
LLM_MODEL = os.getenv("LLM_MODEL", "qwen2.5:3b")
LLM_API_KEY = os.getenv("LLM_API_KEY", "")
LAYER_GENERATION_ENABLED = os.getenv("LAYER_GENERATION_ENABLED", "true").lower() == "true"
completion_provider = CompletionProvider(
base_url=LLM_PROVIDER_URL, api_key=LLM_API_KEY
)
# ── PII Verifier (Presidio precision filter) ──────────────────
# ``noop`` keeps the pre-existing Presidio-only behaviour (community
# default). ``llm`` sends ambiguous candidates (PERSON / LOCATION /
# ORGANIZATION) to the chat endpoint for context-aware filtering.
# The *backend* is OPA-policy-driven at runtime so admins can flip
# via manage_policies without restarting ingestion. The env vars only
# describe WHERE the LLM lives, not WHETHER to call it.
PII_VERIFIER_URL = os.getenv("PII_VERIFIER_URL", LLM_PROVIDER_URL)
PII_VERIFIER_MODEL = os.getenv("PII_VERIFIER_MODEL", LLM_MODEL)
PII_VERIFIER_API_KEY = os.getenv("PII_VERIFIER_API_KEY", LLM_API_KEY)
PII_VERIFIER_ENABLED_DEFAULT = os.getenv("PII_VERIFIER_ENABLED", "false").lower() == "true"
PII_VERIFIER_BACKEND_DEFAULT = os.getenv("PII_VERIFIER_BACKEND", "noop")
PII_VERIFIER_TIMEOUT = float(os.getenv("PII_VERIFIER_TIMEOUT_SECONDS", "15"))
# Lazily-initialised per-backend singletons. OPA policy picks which one
# runs for a given request; we keep the LLM provider warm to avoid
# reconnect costs on repeated ingests.
_pii_verifier_providers: dict[str, Any] = {}
def _get_pii_verifier_provider(backend: str):
"""Return (and cache) the provider instance for the requested backend."""
key = (backend or "noop").lower()
prov = _pii_verifier_providers.get(key)
if prov is not None:
return prov
prov = create_pii_verify_provider(
backend=key,
base_url=PII_VERIFIER_URL,
api_key=PII_VERIFIER_API_KEY,
model=PII_VERIFIER_MODEL,
)
_pii_verifier_providers[key] = prov
return prov
DEFAULT_COLLECTION = "pb_general"
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("pb-ingestion")
# ── Prometheus Metrics ───────────────────────────────────────
# Initialize variables first
pb_ingestion_requests = None
pb_ingestion_duration = None
pb_ingestion_chunks = None
pb_ingestion_pii_entities = None
pb_ingestion_embedding_batch = None
pb_ingestion_pii_verifier_calls = None
pb_ingestion_pii_verifier_duration = None
# Try to create metrics, handle duplicate registration gracefully
try:
pb_ingestion_requests = Counter(
"pb_ingestion_requests_total", "Ingestion requests", ["endpoint", "status"],
)
pb_ingestion_duration = Histogram(
"pb_ingestion_duration_seconds", "Ingestion request duration", ["endpoint"],
buckets=[0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0],
)
pb_ingestion_chunks = Counter(
"pb_ingestion_chunks_total", "Total chunks ingested", ["collection"],
)
pb_ingestion_pii_entities = Counter(
"pb_ingestion_pii_entities_total", "PII entities found", ["entity_type", "action"],
)
pb_ingestion_embedding_batch = Histogram(
"pb_ingestion_embedding_batch_size", "Embedding batch size",
buckets=[1, 5, 10, 20, 50, 100],
)
pb_extract_requests = Counter(
"pb_extract_requests_total", "Document extraction requests",
["status", "extractor"],
)
pb_extract_duration = Histogram(
"pb_extract_duration_seconds", "Document extraction duration",
buckets=[0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0],
)
pb_extract_bytes_in = Histogram(
"pb_extract_bytes_in", "Document extraction input size in bytes",
buckets=[1024, 10_000, 100_000, 500_000, 1_000_000, 5_000_000, 10_000_000, 25_000_000],
)
pb_ingestion_pii_verifier_calls = Counter(
"pb_ingestion_pii_verifier_calls_total",
"Semantic PII verifier decisions (per candidate)",
["entity_type", "backend", "result"],
)
pb_ingestion_pii_verifier_duration = Histogram(
"pb_ingestion_pii_verifier_duration_seconds",
"Semantic PII verifier round-trip duration",
["backend"],
buckets=[0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0],
)
except ValueError as e:
if "Duplicated timeseries" in str(e):
# Metrics already registered, get them from registry
from prometheus_client import REGISTRY
for collector in list(REGISTRY._collector_to_names.keys()):
if hasattr(collector, '_name'):
if collector._name == "pb_ingestion_requests_total":
pb_ingestion_requests = collector
elif collector._name == "pb_ingestion_duration_seconds":
pb_ingestion_duration = collector
elif collector._name == "pb_ingestion_chunks_total":
pb_ingestion_chunks = collector
elif collector._name == "pb_ingestion_pii_entities_total":
pb_ingestion_pii_entities = collector
elif collector._name == "pb_ingestion_embedding_batch_size":
pb_ingestion_embedding_batch = collector
elif collector._name == "pb_extract_requests_total":
pb_extract_requests = collector
elif collector._name == "pb_extract_duration_seconds":
pb_extract_duration = collector
elif collector._name == "pb_extract_bytes_in":
pb_extract_bytes_in = collector
elif collector._name == "pb_ingestion_pii_verifier_calls_total":
pb_ingestion_pii_verifier_calls = collector
elif collector._name == "pb_ingestion_pii_verifier_duration_seconds":
pb_ingestion_pii_verifier_duration = collector
else:
raise
# ── FastAPI App ──────────────────────────────────────────────
app = FastAPI(title="Powerbrain Ingestion API", version="1.0.0")
# ── Service-token auth (B-50, defense-in-depth on top of pb-net) ──
INGESTION_AUTH_TOKEN = read_secret("INGESTION_AUTH_TOKEN", "")
AUTH_REQUIRED = os.getenv("AUTH_REQUIRED", "true").lower() == "true"
SKIP_INGESTION_AUTH_STARTUP_CHECK = (
os.getenv("SKIP_INGESTION_AUTH_STARTUP_CHECK", "false").lower() == "true"
)
# Fail-closed: refuse to start with empty token + AUTH_REQUIRED=true (#126).
verify_ingestion_auth_configured(
INGESTION_AUTH_TOKEN,
auth_required=AUTH_REQUIRED,
skip_check=SKIP_INGESTION_AUTH_STARTUP_CHECK,
service_name="ingestion",
)
from auth_middleware import IngestionAuthMiddleware # noqa: E402
app.add_middleware(IngestionAuthMiddleware, expected_token=INGESTION_AUTH_TOKEN)
# ── Telemetry Initialization ─────────────────────────────────
_ingestion_tracer = init_telemetry("pb-ingestion")
setup_auto_instrumentation(app)
_ingestion_metrics = MetricsAggregator("ingestion")
# ── JSON Metrics Endpoint (must be defined before mount) ─────
@app.get("/metrics/json")
async def metrics_json():
snap = _ingestion_metrics.snapshot()
response = {
"service": "ingestion",
"uptime_seconds": snap["uptime_seconds"],
"requests": {"total": 0, "ok": 0, "error": 0},
"chunks": {"total": 0},
"pii": {"entities_found": {}},
"embedding": {"batch_total": 0},
}
for key, val in snap["raw_metrics"].items():
if "pb_ingestion_requests_total" in key:
if "ok" in key:
response["requests"]["ok"] += val
elif "error" in key:
response["requests"]["error"] += val
elif "pb_ingestion_chunks_total" in key:
response["chunks"]["total"] += val
elif "pb_ingestion_pii_entities_total" in key:
if "entity_type=" in key:
et = key.split("entity_type=")[1].split(",")[0].split("}")[0]
response["pii"]["entities_found"][et] = (
response["pii"]["entities_found"].get(et, 0) + val
)
response["requests"]["total"] = response["requests"]["ok"] + response["requests"]["error"]
return JSONResponse(content=response)
# ── Mount Prometheus Metrics ─────────────────────────────────
metrics_app = prom_make_asgi_app()
app.mount("/metrics", metrics_app)
# ── Clients (lifecycle-managed) ─────────────────────────────
qdrant: AsyncQdrantClient | None = None
http_client: httpx.AsyncClient | None = None
pg_pool: asyncpg.Pool | None = None
# ── Document extraction (shared singleton, markitdown lazy-init on first use) ──
_content_extractor = ContentExtractor()
EXTRACT_MAX_BYTES = int(os.getenv("EXTRACT_MAX_BYTES", str(25 * 1024 * 1024))) # 25 MB
EXTRACT_TIMEOUT_SECONDS = float(os.getenv("EXTRACT_TIMEOUT_SECONDS", "30"))
REQUIRED_OPA_POLICIES = [
"pb/ingestion/quality_gate",
"pb/privacy",
"pb/config/ingestion/pii_verifier",
]
@app.on_event("startup")
async def startup():
global qdrant, http_client, pg_pool
qdrant = AsyncQdrantClient(url=QDRANT_URL)
http_client = httpx.AsyncClient(timeout=60.0)
try:
pg_pool = await asyncpg.create_pool(POSTGRES_URL, min_size=PG_POOL_MIN, max_size=PG_POOL_MAX)
log.info("PostgreSQL pool initialized")
except Exception as e:
log.error(f"PostgreSQL connection failed: {e}")
pg_pool = None
# Fail loudly if required OPA policies are not loaded — otherwise the
# runtime helpers would fail-closed with misleading diagnostics
# (see issue #59: "quality_score 0.629 < required 0.000").
# Disabled only for test runs where OPA is not reachable.
if os.getenv("SKIP_OPA_STARTUP_CHECK", "false").lower() != "true":
try:
await verify_required_policies(http_client, OPA_URL, REQUIRED_OPA_POLICIES)
except Exception as exc:
log.error("OPA startup verification failed: %s", exc)
raise
@app.on_event("shutdown")
async def shutdown():
if pg_pool:
await pg_pool.close()
if http_client:
await http_client.aclose()
# ── Request/Response Models ─────────────────────────────────
class IngestRequest(BaseModel):
source: str
source_type: str | None = "text"
collection: str | None = None
project: str | None = None
classification: str = "internal"
metadata: dict[str, Any] = {}
class SnapshotRequest(BaseModel):
name: str = Field(description="Name of the snapshot")
description: str = Field(default="", description="Description")
created_by: str = Field(default="system", description="Created by")
class ScanRequest(BaseModel):
text: str = Field(min_length=1, description="Text to scan for PII")
language: str = Field(default="de", description="Language of the text (de, en)")
class ScanResponse(BaseModel):
contains_pii: bool = Field(description="Whether PII was detected")
masked_text: str = Field(description="Text with masked PII entities")
entity_types: list[str] = Field(description="List of detected PII types")
class PseudonymizeRequest(BaseModel):
text: str = Field(min_length=1, description="Text to pseudonymize")
salt: str = Field(min_length=1, description="Salt for deterministic pseudonyms")
language: str = Field(default="de", description="Language of the text (de, en)")
class PseudonymizeResponse(BaseModel):
text: str = Field(description="Pseudonymized text")
mapping: dict[str, str] = Field(description="Mapping original → pseudonym")
contains_pii: bool = Field(description="Whether PII was detected")
entity_types: list[str] = Field(description="List of detected PII types")
class ChunkIngestRequest(BaseModel):
"""Request for adapter-based chunk ingestion. Internal use only."""
chunks: list[str]
project: str
collection: str = "pb_general"
classification: str = "internal"
metadata: dict[str, Any] = {}
source: str
source_type: str = "text"
class ExtractRequest(BaseModel):
"""Request for binary document extraction.
Called primarily by pb-proxy for chat attachments, but also usable by any
adapter that needs to convert a binary blob to text via the shared pipeline.
"""
data: str = Field(
min_length=1,
description="Base64-encoded raw bytes of the file",
)
filename: str = Field(
min_length=1,
description="Filename including extension (used to select the extractor)",
)
mime_type: str | None = Field(
default=None,
description="Optional MIME hint (not authoritative; extension takes precedence)",
)
max_bytes: int | None = Field(
default=None,
description="Optional per-request size cap. Always capped by EXTRACT_MAX_BYTES.",
)
class ExtractResponse(BaseModel):
text: str
content_type: str
extractor: str = Field(
description="Backend used: markitdown | fallback | text | ocr | skipped | failed"
)
bytes_in: int
chars_out: int
truncated: bool = False
class PreviewRequest(BaseModel):
"""Dry-run request for the pipeline inspector (demo surface).
Either supply extracted ``text`` directly, or pass base64 ``data``
plus ``filename`` to run the same extractor that a real ingest
would use. No data is persisted — the call touches only the
in-process scanner, quality module, and OPA.
"""
text: str | None = None
data: str | None = Field(default=None, description="Base64 bytes; alternative to `text`")
filename: str | None = None
mime_type: str | None = None
language: str = Field(default="de")
classification: str = Field(default="internal")
source_type: str = Field(default="default")
metadata: dict[str, Any] = Field(default_factory=dict)
legal_basis: str | None = Field(
default=None,
description="Optional hint for OPA privacy.pii_action on confidential data",
)
class PreviewResponse(BaseModel):
"""Flattened view of what every pipeline step would do.
Shape is intentionally optimised for a demo UI — grouped by phase
with booleans / counts the UI can render as badges.
``verifier`` is populated when the semantic PII verifier
(``pb.config.ingestion.pii_verifier.enabled=true``) ran between
the raw Presidio scan and the rest of the pipeline. ``scan``
reflects the post-verifier state so downstream consumers stay
consistent — the ``verifier.before`` sub-field holds the raw
Presidio output for comparison in the demo panel.
"""
extract: dict = Field(default_factory=dict)
scan: dict = Field(default_factory=dict)
verifier: dict = Field(default_factory=dict)
quality: dict = Field(default_factory=dict)
privacy: dict = Field(default_factory=dict)
summary: dict = Field(default_factory=dict)
# ── Helper Functions ────────────────────────────────────────
async def get_embedding(text: str) -> list[float]:
"""Generates embedding via the configured provider (OpenAI-compat), with cache."""
cached = embedding_cache.get(text, EMBEDDING_MODEL)
if cached is not None:
return cached
vector = await embedding_provider.embed(http_client, text, EMBEDDING_MODEL)
embedding_cache.set(text, EMBEDDING_MODEL, vector)
return vector
def chunk_text(text: str, max_chars: int = 1000, overlap: int = 200) -> list[str]:
"""Simple chunking with overlap for long texts."""
if len(text) <= max_chars:
return [text]
chunks = []
start = 0
while start < len(text):
end = start + max_chars
chunks.append(text[start:end])
start = end - overlap
return chunks
async def get_or_create_project_salt(project: str | None) -> str:
"""Gets or creates a salt for the project from pii_vault.project_salts."""
if not pg_pool or not project:
return secrets.token_hex(16)
row = await pg_pool.fetchrow(
"SELECT salt FROM pii_vault.project_salts WHERE project_id = $1",
project,
)
if row:
return row["salt"]
salt = secrets.token_hex(16)
try:
await pg_pool.execute(
"""INSERT INTO pii_vault.project_salts (project_id, salt)
VALUES ($1, $2)
ON CONFLICT (project_id) DO NOTHING""",
project, salt,
)
except Exception as e:
log.warning(f"Project salt creation failed: {e}")
# Re-read to get the winning salt (handles race condition)
row = await pg_pool.fetchrow(
"SELECT salt FROM pii_vault.project_salts WHERE project_id = $1",
project,
)
return row["salt"] if row else salt
async def check_opa_quality_gate(
source_type: str, quality_score: float
) -> dict:
"""Query OPA pb.ingestion.quality_gate (EU AI Act Art. 10).
Returns a dict with ``allowed`` (bool), ``min_score`` (float) and
``reason`` (str). On OPA failure we fail-closed (allowed=False) so a
broken policy engine cannot silently bypass the quality gate.
``min_score`` uses the sentinel ``-1.0`` when the policy package is
not loaded or OPA is unreachable. The normal minimum is never
negative, so ``-1.0`` in logs or the ``ingestion_rejections`` table
flags a configuration problem rather than a threshold comparison.
"""
input_data = {
"source_type": source_type or "default",
"quality_score": float(quality_score),
}
try:
result = await opa_query(
http_client, OPA_URL, "pb/ingestion/quality_gate", input_data,
)
except OpaPolicyMissingError as exc:
log.error("OPA policy missing: %s", exc.package_path)
return {
"allowed": False,
"min_score": -1.0,
"reason": f"opa_policy_missing: {exc.package_path}",
}
except Exception as e:
log.warning("OPA quality_gate check failed, fail-closed: %s", e)
return {"allowed": False, "min_score": -1.0,
"reason": f"opa_unreachable: {e}"}
if not isinstance(result, dict):
log.warning("OPA quality_gate returned non-dict %r, fail-closed", result)
return {"allowed": False, "min_score": -1.0,
"reason": "opa_unexpected_shape"}
return {
"allowed": bool(result.get("allowed", False)),
"min_score": float(result.get("min_score", 0.0)),
"reason": result.get("reason", ""),
}
async def check_opa_pii_verifier() -> dict:
"""Fetch the semantic verifier policy from OPA.
Returns ``{enabled, backend, min_confidence_keep}``. Defaults match
the noop backend so an outage can't accidentally widen what the
verifier drops — fail-closed on policy unreachability.
"""
fallback = {
"enabled": PII_VERIFIER_ENABLED_DEFAULT,
"backend": PII_VERIFIER_BACKEND_DEFAULT,
"min_confidence_keep": 0.5,
}
try:
data = await opa_query(
http_client, OPA_URL, "pb/config/ingestion/pii_verifier",
)
except OpaPolicyMissingError as exc:
log.warning(
"OPA policy %s not loaded — falling back to env defaults "
"(enabled=%s, backend=%s)",
exc.package_path, fallback["enabled"], fallback["backend"],
)
return fallback
except Exception as exc:
log.warning("OPA pii_verifier policy lookup failed, using env defaults: %s", exc)
return fallback
if not isinstance(data, dict):
return fallback
return {
"enabled": bool(data.get("enabled", fallback["enabled"])),
"backend": str(data.get("backend", fallback["backend"])),
"min_confidence_keep": float(
data.get("min_confidence_keep", fallback["min_confidence_keep"])
),
}
async def apply_pii_verifier(
text: str,
contains_pii: bool,
entity_counts: dict[str, int],
entity_locations: list[dict],
) -> tuple[bool, dict[str, int], list[dict], dict]:
"""Run the verifier on a scan result, returning filtered data + stats.
Wraps :meth:`_BasePIIVerifyProvider.verify` with OPA policy,
Prometheus counters, and the telemetry trace span. Safe to call
unconditionally: when the verifier is disabled (noop backend) the
returned arrays are unchanged and ``stats["enabled"]`` is False.
"""
stats_dict: dict = {"enabled": False, "backend": "noop",
"input_count": len(entity_locations)}
policy = await check_opa_pii_verifier()
if not policy["enabled"] or policy["backend"] == "noop" or not entity_locations:
return contains_pii, entity_counts, entity_locations, {
**stats_dict,
"enabled": policy["enabled"],
"backend": policy["backend"],
}
# Build candidates + run. Provider handles pattern vs ambiguous split.
# The *backend* is decided by OPA, so the singleton is looked up per
# call — admins can flip from noop → llm at runtime without needing
# an ingestion restart.
candidates = build_candidates_from_locations(text, entity_locations)
provider = _get_pii_verifier_provider(policy["backend"])
t0 = time.perf_counter()
try:
with trace_operation(_ingestion_tracer, "pii_verify", "ingestion",
backend=policy["backend"],
input_count=len(candidates)):
keep, stats = await provider.verify(
http_client, text, candidates,
)
except Exception as exc:
log.warning("pii_verify_provider raised — falling back to noop: %s", exc)
return contains_pii, entity_counts, entity_locations, {
**stats_dict, "enabled": True, "backend": policy["backend"],
"error": str(exc),
}
duration = time.perf_counter() - t0
# Prometheus
if pb_ingestion_pii_verifier_duration:
pb_ingestion_pii_verifier_duration.labels(backend=stats.backend).observe(duration)
if pb_ingestion_pii_verifier_calls:
for etype, bucket in stats.by_entity_type.items():
for result_name in ("kept", "reverted", "forwarded"):
count = int(bucket.get(result_name, 0))
if count:
pb_ingestion_pii_verifier_calls.labels(
entity_type=etype, backend=stats.backend,
result=result_name,
).inc(count)
new_contains, new_counts, new_locs = apply_verdicts_to_scan_result(
entity_counts, entity_locations, keep,
)
return new_contains, new_counts, new_locs, {
"enabled": True,
"backend": stats.backend,
"input_count": stats.input_count,
"forwarded": stats.forwarded,
"reviewed": stats.reviewed,
"kept": stats.kept,
"reverted": stats.reverted,
"errors": stats.errors,
"duration_ms": round(duration * 1000, 2),
"by_entity_type": stats.by_entity_type,
}
async def check_opa_privacy(
classification: str, contains_pii: bool, legal_basis: str | None = None
) -> dict:
"""Queries OPA for pii_action and dual_storage_enabled.
OPA endpoint: /v1/data/pb/privacy. Fail-closed on missing policy or
unreachable OPA — privacy decisions must never silently default
to a more permissive action than ``block``.
"""
input_data = {
"classification": classification,
"contains_pii": contains_pii,
"legal_basis": legal_basis or "",
}
result = {"pii_action": "block", "dual_storage_enabled": False}
try:
data = await opa_query(http_client, OPA_URL, "pb/privacy", input_data)
except OpaPolicyMissingError as exc:
log.error(
"OPA privacy policy not loaded (%s) — defaulting to block",
exc.package_path,
)
result["reason"] = f"opa_policy_missing: {exc.package_path}"
return result
except Exception as e:
log.warning("OPA privacy check failed, defaulting to block: %s", e)
return result
if isinstance(data, dict):
result["pii_action"] = data.get("pii_action", "block")
result["dual_storage_enabled"] = data.get("dual_storage_enabled", False)
result["retention_days"] = data.get("retention_days", 365)
return result
async def store_in_vault(
doc_id: str,
chunk_index: int,
original_text: str,
pii_entities: list[dict],
mapping: dict[str, str],
salt: str,
retention_days: int,
data_category: str | None,
) -> str:
"""Stores original text + mapping in pii_vault. Returns vault_ref UUID."""
if not pg_pool:
raise RuntimeError("PostgreSQL unavailable for vault storage")
vault_id = str(uuid.uuid4())
expires_at = datetime.now(timezone.utc) + timedelta(days=retention_days)
async with pg_pool.acquire() as conn:
async with conn.transaction():
# Store original
await conn.execute("""
INSERT INTO pii_vault.original_content
(id, document_id, chunk_index, original_text,
pii_entities, retention_expires_at, data_category)
VALUES ($1, $2, $3, $4, $5, $6, $7)
""", vault_id, doc_id, chunk_index, original_text,
json.dumps(pii_entities), expires_at, data_category)
# Store mapping (one entry per entity)
for original, pseudonym in mapping.items():
entity_type = "UNKNOWN"
for e in pii_entities:
if e.get("text") == original:
entity_type = e.get("type", "UNKNOWN")
break
await conn.execute("""
INSERT INTO pii_vault.pseudonym_mapping
(document_id, chunk_index, pseudonym,
entity_type, salt)
VALUES ($1, $2, $3, $4, $5)
""", doc_id, chunk_index, pseudonym, entity_type, salt)
return vault_id
async def log_pii_scan(
source: str,
entities_found: dict,
action_taken: str,
classification: str,
dataset_id: str | None = None,
):
"""Writes an entry to pii_scan_log."""
if not pg_pool:
return
try:
await pg_pool.execute("""
INSERT INTO pii_scan_log
(source, entities_found, action_taken, classification, dataset_id)
VALUES ($1, $2, $3, $4, $5)
""", source, json.dumps(entities_found), action_taken,
classification, dataset_id)
except Exception as e:
log.warning(f"pii_scan_log insert failed: {e}")
L0_SYSTEM_PROMPT = (
"You are a document abstraction engine. Generate a single-sentence abstract "
"(max 100 tokens) that captures the essence of the document. The abstract must "
"enable quick relevance assessment. Do not include specific details — only the "
"topic and scope. Respond with the abstract only, no preamble."
)
L1_SYSTEM_PROMPT = (
"You are a document overview engine. Generate a structured Markdown overview "
"(max 500 tokens) that covers:\n"
"1. What this document is about (1 sentence)\n"
"2. Key sections/topics as bullet points\n"
"3. Most important facts or numbers\n"
"4. What kind of detailed information is available in the full document\n\n"
"The overview enables an AI agent to decide whether to load the full document. "
"Respond with the overview only, no preamble. Use Markdown formatting."
)
async def generate_l0(chunks: list[str], source: str = "", classification: str = "") -> str | None:
"""Generate a short L0 abstract (~100 tokens) from document chunks.
Returns None if LLM is unavailable or generation fails (graceful degradation).
"""
if not LAYER_GENERATION_ENABLED:
return None
try:
full_text = "\n\n".join(chunks)
# Truncate to ~4000 chars to stay within context limits
if len(full_text) > 4000:
full_text = full_text[:4000] + "\n\n[truncated]"
user_prompt = (
f"Document source: {source}\n"
f"Classification: {classification}\n"
f"Full text (from {len(chunks)} chunks):\n\n{full_text}"
)
result = await completion_provider.generate(
http_client,
model=LLM_MODEL,
system_prompt=L0_SYSTEM_PROMPT,
user_prompt=user_prompt,
)
return result
except Exception as e:
log.warning(f"L0 generation failed (graceful degradation): {e}")
return None
async def generate_l1(chunks: list[str], source: str = "", classification: str = "") -> str | None:
"""Generate a structured L1 Markdown overview (~500 tokens) from document chunks.
Returns None if LLM is unavailable or generation fails (graceful degradation).
"""
if not LAYER_GENERATION_ENABLED:
return None
try:
full_text = "\n\n".join(chunks)
# Truncate to ~8000 chars to allow more detail for overview
if len(full_text) > 8000:
full_text = full_text[:8000] + "\n\n[truncated]"
user_prompt = (
f"Document source: {source}\n"
f"Classification: {classification}\n"
f"Full text (from {len(chunks)} chunks):\n\n{full_text}"
)
result = await completion_provider.generate(
http_client,
model=LLM_MODEL,
system_prompt=L1_SYSTEM_PROMPT,
user_prompt=user_prompt,
)
return result
except Exception as e:
log.warning(f"L1 generation failed (graceful degradation): {e}")
return None
async def ingest_text_chunks(
chunks: list[str],
collection: str,
source: str,
classification: str,
project: str | None,
metadata: dict[str, Any],
source_type: str = "text",
) -> dict:
"""Vectorizes chunks and stores them in Qdrant + PostgreSQL.
Pipeline:
1. PII scan of each chunk
2. OPA policy: pii_action + dual_storage_enabled (once per document)
3. Depending on action: mask, pseudonymize+vault, or block
4. Embed + Qdrant upsert
5. PostgreSQL metadata
"""
scanner = get_scanner()
points = []
pii_detected = False
vault_refs: list[str | None] = []
doc_id = str(uuid.uuid4())
processed_texts: list[str] = []
chunk_metadata: list[dict] = []
# Pre-create documents_meta (so that vault FK constraints are satisfied)
if pg_pool:
try:
await pg_pool.execute("""
INSERT INTO documents_meta
(id, title, source, qdrant_collection, classification,
chunk_count, contains_pii, metadata)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
""",
doc_id,
source[:200],
source,
collection,
classification,
0, # chunk_count updated later
False, # contains_pii updated later
json.dumps(metadata),
)
except Exception as e:
log.error(f"PG documents_meta insert failed: {e}")
# Query OPA policy once per document (classification is the same for all chunks)
opa_result: dict | None = None
total_pii_entities = 0
for i, chunk in enumerate(chunks):
# 1. PII-Scan
scan_result = scanner.scan_text(chunk)
vault_ref = None
# Apply semantic verifier when policy enables it. Noop-default
# preserves the pre-existing behaviour for every community
# deployment.
if scan_result.contains_pii:
contains_v, counts_v, locs_v, _vstats = await apply_pii_verifier(
chunk,
scan_result.contains_pii,
dict(scan_result.entity_counts),
list(scan_result.entity_locations),
)
# Replace the scan_result view downstream uses with the
# verifier-filtered one (or keep the original when disabled).
scan_result = type(scan_result)(
contains_pii=contains_v,
entity_counts=counts_v,
entity_locations=locs_v,
)
if scan_result.contains_pii:
pii_detected = True
total_pii_entities += sum(int(c) for c in scan_result.entity_counts.values())
# Track PII entities found
for entity_type, count in scan_result.entity_counts.items():
for _ in range(int(count)):
pb_ingestion_pii_entities.labels(entity_type=entity_type, action="found").inc() if pb_ingestion_pii_entities else None
# 2. OPA Policy: What to do with PII? (only query on first detection)
if opa_result is None:
opa_result = await check_opa_privacy(
classification, True, metadata.get("legal_basis")
)
pii_action = opa_result["pii_action"]
dual_storage = opa_result["dual_storage_enabled"]
retention_days = opa_result.get("retention_days", 365)
if pii_action == "block":
log.warning(
f"PII detected in chunk {i}, classification '{classification}'"
f" → blocked by OPA policy"
)
await log_pii_scan(
source, scan_result.entity_counts, "block", classification
)
return {
"status": "blocked",
"reason": f"PII in {classification} data blocked by policy",
"chunks_ingested": 0,
"pii_detected": True,
}
elif pii_action in ("pseudonymize", "encrypt_and_store") and dual_storage:
# 3a. Dual Storage: pseudonymize + store original in vault
log.info(
f"PII in chunk {i}: {scan_result.entity_counts}"
f" → pseudonymizing (dual storage, action={pii_action})"
)
salt = await get_or_create_project_salt(project)
pseudo_text, mapping = scanner.pseudonymize_text(chunk, salt)
# Vault: Store original + mapping
pii_entities = [
{
"type": loc["type"],
"text": chunk[loc["start"]:loc["end"]],
"start": loc["start"],
"end": loc["end"],
"score": loc["score"],
}
for loc in scan_result.entity_locations
]
if pg_pool:
vault_ref = await store_in_vault(
doc_id, i, chunk, pii_entities, mapping,
salt, retention_days,
metadata.get("data_category"),
)
chunk = pseudo_text
await log_pii_scan(
source, scan_result.entity_counts,
"pseudonymize", classification,
)
else:
# 3b. Fallback: mask (public or dual_storage=false)
if pii_action not in ("mask", "pseudonymize"):
log.warning(
f"PII action '{pii_action}' not fully implemented, "