perucompras-cli 0.1.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.
Files changed (50) hide show
  1. perucompras_cli-0.1.0.dist-info/METADATA +429 -0
  2. perucompras_cli-0.1.0.dist-info/RECORD +50 -0
  3. perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
  4. perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
  6. piloto_ai_cli/__init__.py +51 -0
  7. piloto_ai_cli/__main__.py +5 -0
  8. piloto_ai_cli/api.py +394 -0
  9. piloto_ai_cli/attribute_text.py +106 -0
  10. piloto_ai_cli/attributes_service.py +250 -0
  11. piloto_ai_cli/auto_tag.py +65 -0
  12. piloto_ai_cli/backoff.py +25 -0
  13. piloto_ai_cli/cards.py +871 -0
  14. piloto_ai_cli/cli.py +602 -0
  15. piloto_ai_cli/connectors.py +106 -0
  16. piloto_ai_cli/database.py +491 -0
  17. piloto_ai_cli/enrichment.py +557 -0
  18. piloto_ai_cli/errors.py +92 -0
  19. piloto_ai_cli/excel.py +186 -0
  20. piloto_ai_cli/extraction.py +1316 -0
  21. piloto_ai_cli/health.py +398 -0
  22. piloto_ai_cli/health_workflow.py +1060 -0
  23. piloto_ai_cli/http_client.py +610 -0
  24. piloto_ai_cli/llm_client.py +259 -0
  25. piloto_ai_cli/llm_extraction.py +444 -0
  26. piloto_ai_cli/llm_output.py +90 -0
  27. piloto_ai_cli/pane.py +303 -0
  28. piloto_ai_cli/parsers.py +477 -0
  29. piloto_ai_cli/payload_store.py +227 -0
  30. piloto_ai_cli/pdf_parser.py +12 -0
  31. piloto_ai_cli/py.typed +0 -0
  32. piloto_ai_cli/query_compiler.py +1112 -0
  33. piloto_ai_cli/query_result.py +175 -0
  34. piloto_ai_cli/query_service.py +199 -0
  35. piloto_ai_cli/reextract.py +129 -0
  36. piloto_ai_cli/review.py +217 -0
  37. piloto_ai_cli/rules.py +67 -0
  38. piloto_ai_cli/run_log.py +230 -0
  39. piloto_ai_cli/schema/__init__.py +25 -0
  40. piloto_ai_cli/schema/contract-v1.schema.json +261 -0
  41. piloto_ai_cli/schema/contract.py +257 -0
  42. piloto_ai_cli/schema/migration_filters.py +59 -0
  43. piloto_ai_cli/schema/models.py +747 -0
  44. piloto_ai_cli/schema/snowflake_autogen.py +134 -0
  45. piloto_ai_cli/search_form.py +82 -0
  46. piloto_ai_cli/settings.py +174 -0
  47. piloto_ai_cli/snowflake_url.py +90 -0
  48. piloto_ai_cli/stamp_service.py +53 -0
  49. piloto_ai_cli/sync.py +1157 -0
  50. piloto_ai_cli/unit_converter.py +81 -0
@@ -0,0 +1,1112 @@
1
+ """Compile validated predicates into SQLAlchemy Core queries."""
2
+
3
+ from collections import Counter
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass
6
+ from dataclasses import field as dataclass_field
7
+ from datetime import datetime
8
+ from decimal import Decimal, InvalidOperation
9
+ from typing import Any, cast
10
+
11
+ from sqlalchemy import (
12
+ Boolean,
13
+ Column,
14
+ DateTime,
15
+ Integer,
16
+ MetaData,
17
+ Numeric,
18
+ String,
19
+ Table,
20
+ and_,
21
+ bindparam,
22
+ false,
23
+ func,
24
+ literal,
25
+ or_,
26
+ select,
27
+ true,
28
+ union,
29
+ union_all,
30
+ )
31
+ from sqlalchemy.engine import Connection
32
+ from sqlalchemy.sql import Select
33
+ from sqlalchemy.sql.base import Executable
34
+ from sqlalchemy.sql.elements import ColumnElement
35
+
36
+ from piloto_ai_cli.errors import ContractError, ContractErrorCode
37
+ from piloto_ai_cli.schema.contract import ValidatedContract, ValidatedPredicate
38
+ from piloto_ai_cli.schema.models import SCHEMA, Attribute, AttributeScope, Ficha
39
+ from piloto_ai_cli.unit_converter import UnitConverter
40
+
41
+ _FICHA_VALUE = Table(
42
+ "v_ficha_value",
43
+ MetaData(),
44
+ Column("ficha_id", String()),
45
+ Column("attribute_id", String()),
46
+ Column("kind", String()),
47
+ Column("value_number", Numeric(24, 6)),
48
+ Column("value_unit", String()),
49
+ Column("value_text", String()),
50
+ Column("raw_text", String()),
51
+ Column("source", String()),
52
+ Column("confidence", Numeric(4, 3)),
53
+ schema=SCHEMA,
54
+ )
55
+
56
+ _QUERY_METADATA = MetaData()
57
+ _MEMBER_FICHA = Table(
58
+ "v_member_ficha",
59
+ _QUERY_METADATA,
60
+ Column("ficha_id", String()),
61
+ schema=SCHEMA,
62
+ )
63
+ _DEPARTMENT_FICHA = Table(
64
+ "v_department_ficha",
65
+ _QUERY_METADATA,
66
+ Column("ficha_id", String()),
67
+ Column("department", String()),
68
+ schema=SCHEMA,
69
+ )
70
+ _DEPARTMENT_SYNC = Table(
71
+ "department_sync",
72
+ _QUERY_METADATA,
73
+ Column("agreement_id", String()),
74
+ Column("department", String()),
75
+ Column("excel_stamp", DateTime()),
76
+ schema=SCHEMA,
77
+ )
78
+ # Structural facet name -> ``Ficha`` column; ``department`` is structural too
79
+ # but comes from department membership, not a ``ficha`` column.
80
+ # Stored kinds that carry no value: ``unknown`` (no source gives one) and
81
+ # ``blank`` (a source lists the attribute with an empty or placeholder value).
82
+ _NO_VALUE_KINDS = ("blank", "unknown")
83
+ _FICHA_FACETS = {"catalogue": "catalogue", "category": "category", "agreement": "agreement_id"}
84
+ _STRUCTURAL_FACETS = frozenset({*_FICHA_FACETS, "department"})
85
+ _ATTRIBUTE_SCOPE = Table(
86
+ "attribute_scope",
87
+ _QUERY_METADATA,
88
+ Column("attribute_id", String()),
89
+ Column("category", String()),
90
+ schema=SCHEMA,
91
+ )
92
+ _ATTRIBUTE = Table(
93
+ "attribute",
94
+ _QUERY_METADATA,
95
+ Column("attribute_id", String()),
96
+ Column("merged_into", String()),
97
+ Column("status", String()),
98
+ schema=SCHEMA,
99
+ )
100
+ # Parameter carrying the fetched match ids into ``CompiledQuery.facets`` when
101
+ # rows are returned (see ``CompiledQuery.facets_over_matches``).
102
+ FACET_MATCH_IDS = "facet_match_ids"
103
+ _UNKNOWN = Table(
104
+ "v_unknown",
105
+ _QUERY_METADATA,
106
+ Column("ficha_id", String()),
107
+ Column("attribute_id", String()),
108
+ Column("reason", String()),
109
+ Column("confidence", Numeric(4, 3)),
110
+ schema=SCHEMA,
111
+ )
112
+ _PENDING_PROPOSALS = Table(
113
+ "v_pending_proposals",
114
+ _QUERY_METADATA,
115
+ Column("proposal_type", String()),
116
+ Column("proposal_id", String()),
117
+ Column("status", String()),
118
+ Column("ficha_id", String()),
119
+ Column("attribute_id", String()),
120
+ Column("category", String()),
121
+ schema=SCHEMA,
122
+ )
123
+
124
+
125
+ @dataclass(frozen=True)
126
+ class CompiledQuery:
127
+ """The matching fichas and per-predicate unknowns and scope reports.
128
+
129
+ ``unknown`` rows are ``(ficha_id, predicate_index, attribute_id, reason)``;
130
+ ``predicate_index`` is the predicate's position in the contract, so two
131
+ predicates on the same attribute stay apart.
132
+
133
+ Run it with :meth:`execute`, which reads the department checkpoint before
134
+ and after the result queries so the rows and reports describe the same
135
+ department list. Callers that execute the query statements themselves must
136
+ call :meth:`read_department_as_of` first for a department-scoped query.
137
+
138
+ ``facets`` has two forms. With ``include.rows: false`` it aggregates the
139
+ matching set in the database (the questionnaire's partial counts). When
140
+ rows are returned, it summarises exactly the fichas :meth:`execute`
141
+ fetched: it reads them from the expanding ``facet_match_ids`` parameter
142
+ (``facets_over_matches`` is true), so the facet counts always describe the
143
+ returned match list.
144
+ """
145
+
146
+ matches: Executable
147
+ non_matches: Executable
148
+ unknown: Executable
149
+ not_applicable: Executable
150
+ pending: Executable
151
+ department_as_of: Executable | None = None
152
+ facets: Executable | None = None
153
+ facet_names: tuple[str, ...] = ()
154
+ facets_over_matches: bool = False
155
+
156
+ def read_department_as_of(self, connection: Connection) -> datetime | None:
157
+ """Return the department checkpoint, refusing a pair never synced."""
158
+ if self.department_as_of is None:
159
+ return None
160
+ stamp = connection.execute(self.department_as_of).scalar_one_or_none()
161
+ if stamp is None:
162
+ raise ContractError(
163
+ ContractErrorCode.DEPARTMENT_UNAVAILABLE,
164
+ "scope.department",
165
+ "Department was not synced.",
166
+ )
167
+ return cast(datetime, stamp)
168
+
169
+ def execute(self, connection: Connection, *, max_attempts: int = 3) -> QueryRows:
170
+ """Run the query so its rows and ``department_as_of`` share one checkpoint.
171
+
172
+ A department sync commits ``ficha_department`` and the newer
173
+ ``department_sync.excel_stamp`` together and only ever moves the stamp
174
+ forward, so an unchanged checkpoint before and after the result queries
175
+ means no sync of the pair committed in between. When it changed, the
176
+ rows may mix two lists and the run is repeated.
177
+ """
178
+ if max_attempts < 1:
179
+ raise ValueError("max_attempts must be at least 1")
180
+ for _ in range(max_attempts):
181
+ before = self.read_department_as_of(connection)
182
+ matches = tuple(
183
+ cast(str, ficha_id) for ficha_id in connection.execute(self.matches).scalars()
184
+ )
185
+ unknown = tuple(
186
+ (cast(str, row[0]), cast(int, row[1]), cast(str, row[2]), cast(str, row[3]))
187
+ for row in connection.execute(self.unknown)
188
+ )
189
+ facets = (
190
+ _read_facets(
191
+ self.facet_names,
192
+ connection.execute(
193
+ self.facets,
194
+ {FACET_MATCH_IDS: list(matches)} if self.facets_over_matches else {},
195
+ ),
196
+ )
197
+ if self.facets is not None
198
+ else {}
199
+ )
200
+ not_applicable = tuple(
201
+ NotApplicable(
202
+ attribute_id=cast(str, row[0]),
203
+ checked=cast(int, row[1]),
204
+ pending=cast(int, row[2]),
205
+ )
206
+ for row in connection.execute(self.not_applicable)
207
+ )
208
+ pending_row = connection.execute(self.pending).one()
209
+ # One statement decides the non-match bucket itself (in scope, not a
210
+ # match, not unknown), so a write committed between the reads can
211
+ # never make it negative.
212
+ non_matches = cast(int, connection.execute(self.non_matches).scalar_one())
213
+ if self.read_department_as_of(connection) == before:
214
+ return QueryRows(
215
+ matches=matches,
216
+ non_matches=non_matches,
217
+ unknown=unknown,
218
+ unknown_counts=_count_unknowns(unknown),
219
+ not_applicable=not_applicable,
220
+ pending=PendingCounts(
221
+ card_pending=cast(int, pending_row[0]),
222
+ pdf_pending=cast(int, pending_row[1]),
223
+ extraction_pending=cast(int, pending_row[2]),
224
+ proposals=cast(int, pending_row[3]),
225
+ ),
226
+ department_as_of=before,
227
+ facets=facets,
228
+ )
229
+ raise DepartmentCheckpointChangedError(
230
+ f"The department list changed during each of {max_attempts} attempts."
231
+ )
232
+
233
+
234
+ class DepartmentCheckpointChangedError(RuntimeError):
235
+ """The department checkpoint kept moving while the query ran."""
236
+
237
+
238
+ @dataclass(frozen=True)
239
+ class QueryRows:
240
+ """Rows and reports of one run, consistent with ``department_as_of``."""
241
+
242
+ matches: tuple[str, ...]
243
+ non_matches: int
244
+ unknown: tuple[tuple[str, int, str, str], ...]
245
+ unknown_counts: tuple[UnknownCount, ...]
246
+ not_applicable: tuple[NotApplicable, ...]
247
+ pending: PendingCounts
248
+ department_as_of: datetime | None
249
+ facets: dict[str, FacetSummary] = dataclass_field(default_factory=dict)
250
+
251
+
252
+ @dataclass(frozen=True)
253
+ class FacetValue:
254
+ """One distinct facet value and the number of matching fichas that have it."""
255
+
256
+ value: str | Decimal
257
+ count: int
258
+
259
+
260
+ @dataclass(frozen=True)
261
+ class FacetSummary:
262
+ """Distinct values and separately counted unknown fichas for one facet."""
263
+
264
+ values: tuple[FacetValue, ...]
265
+ unknown_count: int
266
+
267
+
268
+ @dataclass(frozen=True)
269
+ class UnknownCount:
270
+ """One reason count for an unknown predicate."""
271
+
272
+ predicate_index: int
273
+ attribute_id: str
274
+ reason: str
275
+ count: int
276
+
277
+
278
+ @dataclass(frozen=True)
279
+ class NotApplicable:
280
+ """An attribute absent from checked fichas in the scope."""
281
+
282
+ attribute_id: str
283
+ checked: int
284
+ pending: int
285
+
286
+
287
+ @dataclass(frozen=True)
288
+ class PendingCounts:
289
+ """Pending work and proposals in the query scope."""
290
+
291
+ card_pending: int
292
+ pdf_pending: int
293
+ extraction_pending: int
294
+ proposals: int
295
+
296
+
297
+ def _count_unknowns(
298
+ rows: tuple[tuple[str, int, str, str], ...],
299
+ ) -> tuple[UnknownCount, ...]:
300
+ """Count unknown fichas per predicate and reason."""
301
+ counts = Counter((index, attribute_id, reason) for _, index, attribute_id, reason in rows)
302
+ return tuple(
303
+ UnknownCount(index, attribute_id, reason, count)
304
+ for (index, attribute_id, reason), count in sorted(counts.items())
305
+ )
306
+
307
+
308
+ class QueryCompiler:
309
+ """Compile a validated contract against the current ficha-value view."""
310
+
311
+ def __init__(self, unit_converter: UnitConverter, confidence_threshold: float = 0.8) -> None:
312
+ self._unit_converter = unit_converter
313
+ self._confidence_threshold = confidence_threshold
314
+
315
+ def compile(self, contract: ValidatedContract) -> CompiledQuery:
316
+ """Build match and report queries without reading or changing the database.
317
+
318
+ For department scopes, run the result with :meth:`CompiledQuery.execute`
319
+ (or read ``department_as_of`` before executing either query); otherwise a
320
+ never-synced pair looks like no matches.
321
+ """
322
+ threshold = self._threshold(contract)
323
+ matching_conditions: list[ColumnElement[bool]] = []
324
+ unknown_queries: list[Select[str, int, str, str]] = []
325
+ not_applicable_queries: list[Select[str, int, int]] = []
326
+ scope_conditions, department_as_of = _scope_conditions(contract)
327
+
328
+ for index, predicate in enumerate(contract.predicates):
329
+ if predicate.op == "text":
330
+ matching_conditions.append(_text_match(predicate))
331
+ continue
332
+
333
+ predicate_match = self._predicate_match(contract, index, predicate, threshold)
334
+ matching_conditions.append(predicate_match)
335
+
336
+ # Unknown values remain unknown unless a confident value already
337
+ # decides this predicate.
338
+ unknown_candidate = _UNKNOWN.alias(f"unknown_value_{index}")
339
+ unknown_queries.append(
340
+ select(
341
+ Ficha.ficha_id.label("ficha_id"),
342
+ literal(index, type_=Integer()).label("predicate_index"),
343
+ literal(predicate.attribute, type_=String()).label("attribute_id"),
344
+ unknown_candidate.c.reason.label("reason"),
345
+ )
346
+ .join(unknown_candidate, unknown_candidate.c.ficha_id == Ficha.ficha_id)
347
+ .where(
348
+ *scope_conditions,
349
+ unknown_candidate.c.attribute_id == predicate.attribute,
350
+ or_(
351
+ unknown_candidate.c.reason != "low_confidence",
352
+ unknown_candidate.c.confidence < threshold,
353
+ ),
354
+ ~predicate_match,
355
+ )
356
+ .distinct()
357
+ )
358
+
359
+ matches = select(Ficha.ficha_id).distinct().where(*scope_conditions)
360
+ if matching_conditions:
361
+ matches = matches.where(and_(*matching_conditions))
362
+ match_ids = matches.subquery("non_match_excluded_matches")
363
+ matches = matches.order_by(Ficha.ficha_id)
364
+
365
+ unknown = (
366
+ union_all(*unknown_queries)
367
+ if unknown_queries
368
+ else select(
369
+ literal(None, type_=String()).label("ficha_id"),
370
+ literal(None, type_=Integer()).label("predicate_index"),
371
+ literal(None, type_=String()).label("attribute_id"),
372
+ literal(None, type_=String()).label("reason"),
373
+ ).where(false())
374
+ )
375
+ unknown_ids = unknown.subquery("non_match_excluded_unknown")
376
+ non_matches = select(func.count(func.distinct(Ficha.ficha_id))).where(
377
+ *scope_conditions,
378
+ Ficha.ficha_id.not_in(select(match_ids.c.ficha_id)),
379
+ Ficha.ficha_id.not_in(
380
+ select(unknown_ids.c.ficha_id).where(unknown_ids.c.ficha_id.is_not(None))
381
+ ),
382
+ )
383
+ scope_fichas = select(Ficha.ficha_id).where(*scope_conditions)
384
+ checked_count = (
385
+ select(func.count())
386
+ .select_from(Ficha)
387
+ .where(
388
+ *scope_conditions,
389
+ ~Ficha.card_pending,
390
+ ~Ficha.pdf_pending,
391
+ ~Ficha.extraction_pending,
392
+ )
393
+ .scalar_subquery()
394
+ )
395
+ pending_count = (
396
+ select(func.count())
397
+ .select_from(Ficha)
398
+ .where(
399
+ *scope_conditions,
400
+ or_(
401
+ Ficha.card_pending,
402
+ Ficha.pdf_pending,
403
+ Ficha.extraction_pending,
404
+ ),
405
+ )
406
+ .scalar_subquery()
407
+ )
408
+ for attribute_id in dict.fromkeys(
409
+ predicate.attribute for predicate in contract.predicates if predicate.op != "text"
410
+ ):
411
+ has_attribute = or_(
412
+ select(literal(1))
413
+ .select_from(_UNKNOWN)
414
+ .where(
415
+ _UNKNOWN.c.ficha_id.in_(scope_fichas),
416
+ _UNKNOWN.c.attribute_id == attribute_id,
417
+ )
418
+ .exists(),
419
+ select(literal(1))
420
+ .select_from(_FICHA_VALUE)
421
+ .where(
422
+ _FICHA_VALUE.c.ficha_id.in_(scope_fichas),
423
+ _FICHA_VALUE.c.attribute_id == attribute_id,
424
+ )
425
+ .exists(),
426
+ )
427
+ not_applicable_queries.append(
428
+ select(
429
+ literal(attribute_id, type_=String()).label("attribute_id"),
430
+ checked_count.label("checked"),
431
+ pending_count.label("pending"),
432
+ ).where(checked_count + pending_count > 0, ~has_attribute)
433
+ )
434
+ not_applicable = (
435
+ union_all(*not_applicable_queries)
436
+ if not_applicable_queries
437
+ else select(
438
+ literal(None, type_=String()).label("attribute_id"),
439
+ literal(None, type_=Integer()).label("checked"),
440
+ literal(None, type_=Integer()).label("pending"),
441
+ ).where(false())
442
+ )
443
+
444
+ # A proposal touches the scope through its extraction's ficha, its
445
+ # category, or its attribute: one applicable to the scope's categories
446
+ # (``attribute_scope``) or named by a predicate, compared by canonical
447
+ # root so merged attribute ids count too.
448
+ attribute_table = cast(Table, Attribute.__table__)
449
+ roots = (
450
+ select(
451
+ attribute_table.c.attribute_id.label("attribute_id"),
452
+ attribute_table.c.attribute_id.label("root_id"),
453
+ )
454
+ .where(attribute_table.c.merged_into.is_(None))
455
+ .cte("proposal_attribute_roots", recursive=True)
456
+ )
457
+ child = attribute_table.alias("proposal_attribute_child")
458
+ roots = roots.union_all(
459
+ select(child.c.attribute_id, roots.c.root_id).where(
460
+ child.c.merged_into == roots.c.attribute_id
461
+ )
462
+ )
463
+ scope_categories = select(Ficha.category).where(*scope_conditions)
464
+ scope_attribute = roots.alias("scope_attribute_root")
465
+ relevant_root_queries: list[Select[Any]] = [
466
+ select(scope_attribute.c.root_id)
467
+ .join(
468
+ AttributeScope,
469
+ AttributeScope.attribute_id == scope_attribute.c.attribute_id,
470
+ )
471
+ .where(AttributeScope.category.in_(scope_categories))
472
+ ]
473
+ if attributes := tuple(
474
+ dict.fromkeys(predicate.attribute for predicate in contract.predicates)
475
+ ):
476
+ predicate_attribute = roots.alias("predicate_attribute_root")
477
+ relevant_root_queries.append(
478
+ select(predicate_attribute.c.root_id).where(
479
+ predicate_attribute.c.attribute_id.in_(attributes)
480
+ )
481
+ )
482
+ relevant_roots = union_all(*relevant_root_queries)
483
+
484
+ proposal_attribute = roots.alias("proposal_attribute_root")
485
+ proposal_scope = or_(
486
+ _PENDING_PROPOSALS.c.ficha_id.in_(scope_fichas),
487
+ _PENDING_PROPOSALS.c.category == "*",
488
+ _PENDING_PROPOSALS.c.category.in_(scope_categories),
489
+ select(literal(1))
490
+ .select_from(proposal_attribute)
491
+ .where(
492
+ proposal_attribute.c.attribute_id == _PENDING_PROPOSALS.c.attribute_id,
493
+ proposal_attribute.c.root_id.in_(relevant_roots),
494
+ )
495
+ .exists(),
496
+ )
497
+ scoped_proposals = (
498
+ select(_PENDING_PROPOSALS.c.proposal_type, _PENDING_PROPOSALS.c.proposal_id)
499
+ .where(_PENDING_PROPOSALS.c.status == "proposed", proposal_scope)
500
+ .distinct()
501
+ .subquery()
502
+ )
503
+ proposal_count = select(func.count()).select_from(scoped_proposals).scalar_subquery()
504
+ pending = select(
505
+ select(func.count())
506
+ .select_from(Ficha)
507
+ .where(*scope_conditions, Ficha.card_pending)
508
+ .scalar_subquery()
509
+ .label("card_pending"),
510
+ select(func.count())
511
+ .select_from(Ficha)
512
+ .where(*scope_conditions, Ficha.pdf_pending)
513
+ .scalar_subquery()
514
+ .label("pdf_pending"),
515
+ select(func.count())
516
+ .select_from(Ficha)
517
+ .where(*scope_conditions, Ficha.extraction_pending)
518
+ .scalar_subquery()
519
+ .label("extraction_pending"),
520
+ proposal_count.label("proposals"),
521
+ )
522
+ # Returned rows get facets computed over exactly the fetched match ids;
523
+ # a counts-only query (``rows: false``) aggregates the matching set in
524
+ # the database.
525
+ facets_over_matches = (contract.include or {}).get("rows", True) is not False
526
+ facet_source: Select[Any] = (
527
+ select(Ficha.ficha_id).where(
528
+ Ficha.ficha_id.in_(bindparam(FACET_MATCH_IDS, expanding=True))
529
+ )
530
+ if facets_over_matches
531
+ else matches
532
+ )
533
+ facets, facet_names = self._compile_facets(contract, facet_source, threshold)
534
+ return CompiledQuery(
535
+ matches=matches,
536
+ non_matches=non_matches,
537
+ unknown=unknown,
538
+ not_applicable=not_applicable,
539
+ pending=pending,
540
+ department_as_of=department_as_of,
541
+ facets=facets,
542
+ facet_names=facet_names,
543
+ facets_over_matches=facets_over_matches and facets is not None,
544
+ )
545
+
546
+ def _compile_facets(
547
+ self,
548
+ contract: ValidatedContract,
549
+ matches: Select[Any],
550
+ threshold: float,
551
+ ) -> tuple[Executable | None, tuple[str, ...]]:
552
+ include = contract.include or {}
553
+ requested = include.get("facets")
554
+ if requested is None:
555
+ return None, ()
556
+
557
+ match_ids = matches.cte("facet_matches")
558
+ queries: list[Select[Any]] = []
559
+ if requested == "all":
560
+ selected_attributes = self._applicable_facet_attributes(match_ids)
561
+ facet_names: tuple[str, ...] = ()
562
+ else:
563
+ facet_names = tuple(dict.fromkeys(cast(list[str], requested)))
564
+ # Structural fields facet from what sync already stored, so they
565
+ # never need enrichment: catalogue, category and agreement from
566
+ # ``ficha``, department from current ``v_department_ficha`` membership.
567
+ for name in (name for name in facet_names if name in _FICHA_FACETS):
568
+ column = getattr(Ficha, _FICHA_FACETS[name])
569
+ queries.append(
570
+ _facet_value_query(
571
+ literal(name, type_=String()),
572
+ literal(None, type_=Numeric(24, 6)),
573
+ column,
574
+ literal(False, type_=Boolean()),
575
+ match_ids,
576
+ Ficha.ficha_id,
577
+ )
578
+ )
579
+ queries.append(
580
+ _facet_unknown_query(
581
+ literal(name, type_=String()),
582
+ match_ids,
583
+ Ficha.ficha_id,
584
+ column.is_(None),
585
+ )
586
+ )
587
+ if "department" in facet_names:
588
+ queries.extend(_department_facet_queries(match_ids))
589
+
590
+ attribute_names = tuple(name for name in facet_names if name not in _STRUCTURAL_FACETS)
591
+ if not attribute_names:
592
+ return union_all(*queries) if queries else None, facet_names
593
+ selected_attributes = self._requested_facet_attributes(attribute_names)
594
+
595
+ queries.extend(_attribute_facet_queries(selected_attributes, match_ids, threshold))
596
+ return (union_all(*queries) if queries else None), facet_names
597
+
598
+ @staticmethod
599
+ def _attribute_roots() -> Any:
600
+ roots = (
601
+ select(
602
+ _ATTRIBUTE.c.attribute_id.label("source_attribute_id"),
603
+ _ATTRIBUTE.c.attribute_id.label("canonical_attribute_id"),
604
+ )
605
+ .where(_ATTRIBUTE.c.merged_into.is_(None))
606
+ .cte("facet_attribute_roots", recursive=True)
607
+ )
608
+ child = _ATTRIBUTE.alias("facet_attribute_child")
609
+ return roots.union_all(
610
+ select(child.c.attribute_id, roots.c.canonical_attribute_id).where(
611
+ child.c.merged_into == roots.c.source_attribute_id
612
+ )
613
+ )
614
+
615
+ def _applicable_facet_attributes(self, match_ids: Any) -> Any:
616
+ roots = self._attribute_roots()
617
+ canonical = _ATTRIBUTE.alias("facet_canonical_attribute")
618
+ return (
619
+ select(
620
+ roots.c.canonical_attribute_id.label("attribute_id"),
621
+ roots.c.canonical_attribute_id.label("facet"),
622
+ )
623
+ .select_from(
624
+ match_ids.join(Ficha, Ficha.ficha_id == match_ids.c.ficha_id)
625
+ .join(_ATTRIBUTE_SCOPE, _ATTRIBUTE_SCOPE.c.category == Ficha.category)
626
+ .join(
627
+ roots,
628
+ roots.c.source_attribute_id == _ATTRIBUTE_SCOPE.c.attribute_id,
629
+ )
630
+ .join(
631
+ canonical,
632
+ canonical.c.attribute_id == roots.c.canonical_attribute_id,
633
+ )
634
+ )
635
+ .where(canonical.c.status == "accepted")
636
+ .distinct()
637
+ .subquery("applicable_facet_attributes")
638
+ )
639
+
640
+ def _requested_facet_attributes(self, names: tuple[str, ...]) -> Any:
641
+ roots = self._attribute_roots()
642
+ canonical = _ATTRIBUTE.alias("requested_canonical_attribute")
643
+ # One query for every requested name, labelled by the name itself, so
644
+ # a long facet list never grows into a compound SELECT per attribute.
645
+ return (
646
+ select(
647
+ roots.c.source_attribute_id.label("facet"),
648
+ roots.c.canonical_attribute_id.label("attribute_id"),
649
+ )
650
+ .select_from(
651
+ roots.join(
652
+ canonical,
653
+ canonical.c.attribute_id == roots.c.canonical_attribute_id,
654
+ )
655
+ )
656
+ .where(
657
+ roots.c.source_attribute_id.in_(names),
658
+ canonical.c.status == "accepted",
659
+ )
660
+ .subquery("requested_facet_attributes")
661
+ )
662
+
663
+ def still_matching(self, contract: ValidatedContract) -> Select[str]:
664
+ """Select the scope's fichas that no predicate rules out yet.
665
+
666
+ A predicate rules a ficha out only when the ficha's current values decide
667
+ it: a text predicate on the description, or a predicate on an attribute
668
+ that has a current value (``v_ficha_value``, an ``unknown``-kind absence
669
+ included) and no confident value that matches. A ficha with no current
670
+ value for the predicate's attribute is unresolved and still matching:
671
+ enrichment may still decide it. Builds the statement only; the caller runs it.
672
+ """
673
+ threshold = self._threshold(contract)
674
+ scope_conditions, _ = _scope_conditions(contract)
675
+ conditions: list[ColumnElement[bool]] = []
676
+ for index, predicate in enumerate(contract.predicates):
677
+ if predicate.op == "text":
678
+ conditions.append(_text_match(predicate))
679
+ continue
680
+ current = _FICHA_VALUE.alias(f"current_value_{index}")
681
+ unresolved = ~(
682
+ select(literal(1))
683
+ .select_from(current)
684
+ .where(
685
+ current.c.ficha_id == Ficha.ficha_id,
686
+ current.c.attribute_id == predicate.attribute,
687
+ )
688
+ .exists()
689
+ )
690
+ conditions.append(
691
+ or_(self._predicate_match(contract, index, predicate, threshold), unresolved)
692
+ )
693
+ return select(Ficha.ficha_id).where(*scope_conditions, *conditions)
694
+
695
+ def _threshold(self, contract: ValidatedContract) -> float | int:
696
+ return (
697
+ contract.confidence_threshold
698
+ if contract.confidence_threshold is not None
699
+ else self._confidence_threshold
700
+ )
701
+
702
+ def _predicate_match(
703
+ self,
704
+ contract: ValidatedContract,
705
+ index: int,
706
+ predicate: ValidatedPredicate,
707
+ threshold: float | int,
708
+ ) -> ColumnElement[bool]:
709
+ """Whether a confident current value decides an attribute predicate true."""
710
+ candidate = _FICHA_VALUE.alias(f"value_{index}")
711
+ matches_predicate = self._predicate_expression(candidate, predicate, contract, index)
712
+ candidate_base = and_(
713
+ candidate.c.ficha_id == Ficha.ficha_id,
714
+ candidate.c.attribute_id == predicate.attribute,
715
+ candidate.c.kind.not_in(_NO_VALUE_KINDS),
716
+ )
717
+ predicate_match: ColumnElement[bool] = (
718
+ select(literal(1))
719
+ .select_from(candidate)
720
+ .where(
721
+ candidate_base,
722
+ candidate.c.confidence >= threshold,
723
+ matches_predicate,
724
+ )
725
+ .exists()
726
+ )
727
+ if predicate.op == "!=":
728
+ # Only confident values decide: a tentative equal value must not
729
+ # veto the match (it is reported as unknown instead).
730
+ predicate_match = and_(
731
+ predicate_match,
732
+ ~select(literal(1))
733
+ .select_from(candidate)
734
+ .where(candidate_base, candidate.c.confidence >= threshold, ~matches_predicate)
735
+ .exists(),
736
+ )
737
+ return predicate_match
738
+
739
+ def _predicate_expression(
740
+ self,
741
+ value: Any,
742
+ predicate: ValidatedPredicate,
743
+ contract: ValidatedContract,
744
+ index: int,
745
+ ) -> ColumnElement[bool]:
746
+ if predicate.op == "exists":
747
+ return literal(True)
748
+ if predicate.op in {"between", "in"}:
749
+ assert predicate.values is not None
750
+ operands: Sequence[Any] = predicate.values
751
+ else:
752
+ assert predicate.value is not None
753
+ operands = (predicate.value,)
754
+
755
+ if (
756
+ predicate.kind == "set"
757
+ and predicate.canonical_unit is not None
758
+ and predicate.op == "in"
759
+ ):
760
+ # A set with a unit stores numeric members in value_number and text
761
+ # members in value_text; an `in` list may hold both.
762
+ numbers = [operand for operand in operands if _is_number(operand)]
763
+ texts = [operand for operand in operands if not _is_number(operand)]
764
+ memberships: list[ColumnElement[bool]] = []
765
+ if numbers:
766
+ memberships.append(
767
+ value.c.value_number.in_(
768
+ [
769
+ self._convert_operand(number, predicate, contract, index)
770
+ for number in numbers
771
+ ]
772
+ )
773
+ )
774
+ if texts:
775
+ memberships.append(value.c.value_text.in_(texts))
776
+ return or_(*memberships)
777
+
778
+ converted: Sequence[Any]
779
+ if predicate.kind == "quantity" or _is_numeric_set(predicate, operands):
780
+ converted = [
781
+ self._convert_operand(operand, predicate, contract, index) for operand in operands
782
+ ]
783
+ column_ = value.c.value_number
784
+ if predicate.op in {"in", "contains"}:
785
+ return cast(ColumnElement[bool], column_.in_(converted))
786
+ if predicate.op == "between":
787
+ return cast(ColumnElement[bool], column_.between(converted[0], converted[1]))
788
+ else:
789
+ if predicate.kind == "flag":
790
+ converted = [
791
+ ("sí" if operand else "no") if isinstance(operand, bool) else operand
792
+ for operand in operands
793
+ ]
794
+ else:
795
+ converted = list(operands)
796
+ column_ = value.c.value_text
797
+ if predicate.op == "in":
798
+ return cast(ColumnElement[bool], column_.in_(converted))
799
+ if predicate.op == "contains":
800
+ return cast(ColumnElement[bool], column_ == converted[0])
801
+
802
+ operand = converted[0]
803
+ if predicate.op == "=":
804
+ return cast(ColumnElement[bool], column_ == operand)
805
+ if predicate.op == "!=":
806
+ return cast(ColumnElement[bool], column_ != operand)
807
+ if predicate.op == "<":
808
+ return cast(ColumnElement[bool], column_ < operand)
809
+ if predicate.op == "<=":
810
+ return cast(ColumnElement[bool], column_ <= operand)
811
+ if predicate.op == ">":
812
+ return cast(ColumnElement[bool], column_ > operand)
813
+ if predicate.op == ">=":
814
+ return cast(ColumnElement[bool], column_ >= operand)
815
+ raise ValueError(f"Unsupported predicate operator: {predicate.op}")
816
+
817
+ def _convert_operand(
818
+ self,
819
+ operand: Any,
820
+ predicate: ValidatedPredicate,
821
+ contract: ValidatedContract,
822
+ index: int,
823
+ ) -> Decimal:
824
+ if isinstance(operand, bool) or predicate.canonical_unit is None:
825
+ raise ContractError(
826
+ ContractErrorCode.SCHEMA_VIOLATION,
827
+ index,
828
+ "A quantity predicate requires a numeric value and canonical unit.",
829
+ )
830
+ try:
831
+ quantity = Decimal(str(operand))
832
+ except (InvalidOperation, ValueError) as error:
833
+ raise ContractError(
834
+ ContractErrorCode.SCHEMA_VIOLATION,
835
+ index,
836
+ "A quantity predicate requires a numeric value.",
837
+ ) from error
838
+ category = contract.scope.get("category", "*")
839
+ return self._unit_converter.convert(
840
+ quantity,
841
+ predicate.unit or predicate.canonical_unit,
842
+ predicate.canonical_unit,
843
+ category,
844
+ location=index,
845
+ )
846
+
847
+
848
+ def _scope_conditions(
849
+ contract: ValidatedContract,
850
+ ) -> tuple[list[ColumnElement[bool]], Executable | None]:
851
+ """Membership and structural scope conditions, and the department checkpoint read."""
852
+ if department := contract.scope.get("department"):
853
+ agreement = contract.scope.get("agreement")
854
+ if agreement is None:
855
+ raise ContractError(
856
+ ContractErrorCode.SCHEMA_VIOLATION,
857
+ "scope.agreement",
858
+ "Department scope requires an agreement.",
859
+ )
860
+ membership = _DEPARTMENT_FICHA
861
+ membership_conditions = [
862
+ membership.c.ficha_id == Ficha.ficha_id,
863
+ membership.c.department == department,
864
+ ]
865
+ department_as_of: Executable | None = select(_DEPARTMENT_SYNC.c.excel_stamp).where(
866
+ _DEPARTMENT_SYNC.c.agreement_id == agreement,
867
+ _DEPARTMENT_SYNC.c.department == department,
868
+ )
869
+ else:
870
+ membership = _MEMBER_FICHA
871
+ membership_conditions = [membership.c.ficha_id == Ficha.ficha_id]
872
+ department_as_of = None
873
+
874
+ scope_conditions: list[ColumnElement[bool]] = [
875
+ select(literal(1)).select_from(membership).where(*membership_conditions).exists()
876
+ ]
877
+ for field, column in (
878
+ ("agreement", Ficha.agreement_id),
879
+ ("catalogue", Ficha.catalogue),
880
+ ("category", Ficha.category),
881
+ ):
882
+ if field in contract.scope:
883
+ scope_conditions.append(column == contract.scope[field])
884
+ return scope_conditions, department_as_of
885
+
886
+
887
+ def _text_match(predicate: ValidatedPredicate) -> ColumnElement[bool]:
888
+ assert isinstance(predicate.value, str)
889
+ return Ficha.description.icontains(predicate.value, autoescape=True)
890
+
891
+
892
+ def _attribute_facet_queries(
893
+ selected_attributes: Any,
894
+ match_ids: Any,
895
+ threshold: float,
896
+ ) -> list[Select[Any]]:
897
+ values = _FICHA_VALUE.alias("facet_value")
898
+ values_query = (
899
+ select(
900
+ selected_attributes.c.facet.label("facet"),
901
+ values.c.value_number.label("value_number"),
902
+ values.c.value_text.label("value_text"),
903
+ literal(False, type_=Boolean()).label("is_unknown"),
904
+ func.count(func.distinct(match_ids.c.ficha_id)).label("count"),
905
+ )
906
+ .select_from(
907
+ selected_attributes.join(
908
+ values,
909
+ values.c.attribute_id == selected_attributes.c.attribute_id,
910
+ ).join(match_ids, match_ids.c.ficha_id == values.c.ficha_id)
911
+ )
912
+ .where(
913
+ values.c.kind.not_in(_NO_VALUE_KINDS),
914
+ values.c.confidence >= threshold,
915
+ or_(values.c.value_number.is_not(None), values.c.value_text.is_not(None)),
916
+ )
917
+ .group_by(
918
+ selected_attributes.c.facet,
919
+ values.c.value_number,
920
+ values.c.value_text,
921
+ )
922
+ )
923
+
924
+ # Unknown fichas: v_unknown rows (low-confidence ones only below the
925
+ # threshold) plus fichas holding a raw-only value, which has no typed value
926
+ # to show whatever the threshold. The union keeps each ficha once per facet.
927
+ unknown = _UNKNOWN.alias("facet_unknown")
928
+ raw_only = _FICHA_VALUE.alias("facet_raw_only_value")
929
+ unknown_fichas = union(
930
+ select(
931
+ selected_attributes.c.facet.label("facet"),
932
+ unknown.c.ficha_id.label("ficha_id"),
933
+ )
934
+ .select_from(
935
+ selected_attributes.join(
936
+ unknown,
937
+ unknown.c.attribute_id == selected_attributes.c.attribute_id,
938
+ )
939
+ )
940
+ .where(
941
+ or_(
942
+ unknown.c.reason != "low_confidence",
943
+ unknown.c.confidence < threshold,
944
+ )
945
+ ),
946
+ select(
947
+ selected_attributes.c.facet.label("facet"),
948
+ raw_only.c.ficha_id.label("ficha_id"),
949
+ )
950
+ .select_from(
951
+ selected_attributes.join(
952
+ raw_only,
953
+ raw_only.c.attribute_id == selected_attributes.c.attribute_id,
954
+ )
955
+ )
956
+ .where(
957
+ raw_only.c.kind.not_in(_NO_VALUE_KINDS),
958
+ raw_only.c.value_number.is_(None),
959
+ raw_only.c.value_text.is_(None),
960
+ ),
961
+ ).subquery("facet_unknown_fichas")
962
+ unknown_query = (
963
+ select(
964
+ unknown_fichas.c.facet.label("facet"),
965
+ literal(None, type_=Numeric(24, 6)).label("value_number"),
966
+ literal(None, type_=String()).label("value_text"),
967
+ literal(True, type_=Boolean()).label("is_unknown"),
968
+ func.count(func.distinct(match_ids.c.ficha_id)).label("count"),
969
+ )
970
+ .select_from(
971
+ unknown_fichas.join(match_ids, match_ids.c.ficha_id == unknown_fichas.c.ficha_id)
972
+ )
973
+ .group_by(unknown_fichas.c.facet)
974
+ )
975
+ return [values_query, unknown_query]
976
+
977
+
978
+ def _department_facet_queries(match_ids: Any) -> list[Select[Any]]:
979
+ """Count matching fichas per department, unknowns from missing checkpoints.
980
+
981
+ Values are the departments where a ficha is **yes** (current
982
+ ``v_department_ficha`` membership). Membership is only known per
983
+ (agreement, department) checkpoint (data-model §4 "Department
984
+ availability"), so a ficha's departments are unknown while its agreement
985
+ lacks a ``department_sync`` row for any surveyed department (one synced
986
+ for some agreement) or has none at all. A ficha that is **no** in every
987
+ synced department is known, not unknown.
988
+ """
989
+ membership = _DEPARTMENT_FICHA.alias("facet_department")
990
+ values_query = (
991
+ select(
992
+ literal("department", type_=String()).label("facet"),
993
+ literal(None, type_=Numeric(24, 6)).label("value_number"),
994
+ membership.c.department.label("value_text"),
995
+ literal(False, type_=Boolean()).label("is_unknown"),
996
+ func.count(func.distinct(match_ids.c.ficha_id)).label("count"),
997
+ )
998
+ .select_from(membership.join(match_ids, match_ids.c.ficha_id == membership.c.ficha_id))
999
+ .group_by(membership.c.department)
1000
+ )
1001
+ surveyed = select(_DEPARTMENT_SYNC.c.department).distinct().subquery("surveyed_department")
1002
+ agreement_sync = _DEPARTMENT_SYNC.alias("facet_agreement_sync")
1003
+ unknown_query = (
1004
+ select(
1005
+ literal("department", type_=String()).label("facet"),
1006
+ literal(None, type_=Numeric(24, 6)).label("value_number"),
1007
+ literal(None, type_=String()).label("value_text"),
1008
+ literal(True, type_=Boolean()).label("is_unknown"),
1009
+ func.count(func.distinct(match_ids.c.ficha_id)).label("count"),
1010
+ )
1011
+ # Joins, not correlated EXISTS under OR (Snowflake rejects those): pair
1012
+ # each matching ficha with every surveyed department and keep it when
1013
+ # its agreement has no checkpoint for one of them. The outer join on
1014
+ # TRUE keeps one row with a NULL department when nothing was surveyed
1015
+ # yet, so every ficha is unknown then.
1016
+ .select_from(
1017
+ match_ids.join(Ficha, Ficha.ficha_id == match_ids.c.ficha_id)
1018
+ .outerjoin(surveyed, true())
1019
+ .outerjoin(
1020
+ agreement_sync,
1021
+ and_(
1022
+ agreement_sync.c.agreement_id == Ficha.agreement_id,
1023
+ agreement_sync.c.department == surveyed.c.department,
1024
+ ),
1025
+ )
1026
+ )
1027
+ .where(agreement_sync.c.agreement_id.is_(None))
1028
+ )
1029
+ return [values_query, unknown_query]
1030
+
1031
+
1032
+ def _facet_value_query(
1033
+ facet: ColumnElement[str],
1034
+ value_number: ColumnElement[Any],
1035
+ value_text: ColumnElement[Any],
1036
+ is_unknown: ColumnElement[bool],
1037
+ match_ids: Any,
1038
+ ficha_id: Any,
1039
+ ) -> Any:
1040
+ return (
1041
+ select(
1042
+ facet.label("facet"),
1043
+ value_number.label("value_number"),
1044
+ value_text.label("value_text"),
1045
+ is_unknown.label("is_unknown"),
1046
+ func.count(func.distinct(match_ids.c.ficha_id)).label("count"),
1047
+ )
1048
+ .select_from(Ficha.__table__.join(match_ids, ficha_id == match_ids.c.ficha_id))
1049
+ .where(value_text.is_not(None))
1050
+ .group_by(facet, value_text)
1051
+ )
1052
+
1053
+
1054
+ def _facet_unknown_query(
1055
+ facet: ColumnElement[str],
1056
+ match_ids: Any,
1057
+ ficha_id: Any,
1058
+ is_unknown: ColumnElement[bool],
1059
+ ) -> Any:
1060
+ return (
1061
+ select(
1062
+ facet.label("facet"),
1063
+ literal(None, type_=Numeric(24, 6)).label("value_number"),
1064
+ literal(None, type_=String()).label("value_text"),
1065
+ literal(True, type_=Boolean()).label("is_unknown"),
1066
+ func.count(func.distinct(match_ids.c.ficha_id)).label("count"),
1067
+ )
1068
+ .select_from(Ficha.__table__.join(match_ids, ficha_id == match_ids.c.ficha_id))
1069
+ .where(is_unknown)
1070
+ .group_by(facet)
1071
+ )
1072
+
1073
+
1074
+ def _read_facets(names: tuple[str, ...], rows: Any) -> dict[str, FacetSummary]:
1075
+ values: dict[str, list[FacetValue]] = {name: [] for name in names}
1076
+ unknown_counts: dict[str, int] = dict.fromkeys(names, 0)
1077
+ for row in rows:
1078
+ facet = cast(str, row.facet)
1079
+ values.setdefault(facet, [])
1080
+ unknown_counts.setdefault(facet, 0)
1081
+ if row.is_unknown:
1082
+ unknown_counts[facet] = cast(int, row.count)
1083
+ else:
1084
+ value = row.value_number if row.value_number is not None else row.value_text
1085
+ if value is not None:
1086
+ values[facet].append(FacetValue(cast(str | Decimal, value), cast(int, row.count)))
1087
+
1088
+ def value_sort_key(item: FacetValue) -> tuple[int, Decimal | str, str]:
1089
+ if isinstance(item.value, Decimal):
1090
+ return (0, item.value, "")
1091
+ return (1, item.value.casefold(), item.value)
1092
+
1093
+ return {
1094
+ facet: FacetSummary(
1095
+ values=tuple(sorted(facet_values, key=value_sort_key)),
1096
+ unknown_count=unknown_counts[facet],
1097
+ )
1098
+ for facet, facet_values in sorted(values.items())
1099
+ }
1100
+
1101
+
1102
+ def _is_numeric_set(predicate: ValidatedPredicate, operands: Sequence[Any]) -> bool:
1103
+ """A set with a canonical unit stores numeric members in ``value_number``."""
1104
+ return (
1105
+ predicate.kind == "set"
1106
+ and predicate.canonical_unit is not None
1107
+ and all(_is_number(operand) for operand in operands)
1108
+ )
1109
+
1110
+
1111
+ def _is_number(operand: Any) -> bool:
1112
+ return isinstance(operand, int | float) and not isinstance(operand, bool)