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
piloto_ai_cli/cards.py ADDED
@@ -0,0 +1,871 @@
1
+ """Synchronize ficha card observations for current Excel members."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import math
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from datetime import UTC, datetime, timedelta
10
+ from typing import Any, NamedTuple, cast
11
+ from uuid import NAMESPACE_URL, uuid5
12
+
13
+ import httpx2
14
+ from sqlalchemy import CursorResult, and_, case, exists, func, null, or_, select, update
15
+ from sqlalchemy.orm import Session, sessionmaker
16
+
17
+ from piloto_ai_cli.backoff import backoff, validate_backoff
18
+ from piloto_ai_cli.connectors import post_search_response
19
+ from piloto_ai_cli.database import chunks, upsert
20
+ from piloto_ai_cli.errors import InvalidExtractionInputError, ParseError
21
+ from piloto_ai_cli.extraction import card_features_equal, rebuild_card_input
22
+ from piloto_ai_cli.http_client import RETRYABLE_STATUSES, HttpClient
23
+ from piloto_ai_cli.pane import seed_filter_pane
24
+ from piloto_ai_cli.parsers import ParsedCard, parse_card, parse_cards, parse_filter_pane
25
+ from piloto_ai_cli.payload_store import PayloadStore
26
+ from piloto_ai_cli.schema.models import (
27
+ Agreement,
28
+ DepartmentSync,
29
+ Ficha,
30
+ FichaCard,
31
+ FichaDepartment,
32
+ Payload,
33
+ )
34
+ from piloto_ai_cli.search_form import ScopeValue, SearchForm
35
+
36
+ _INPUT_HASH_ATTEMPTS = 3
37
+ _LOGGER = logging.getLogger(__name__)
38
+ _PAGE_SIZE = 12
39
+ # Statuses that say the attempt failed, not what the site answers about this
40
+ # lookup: the client's retryable statuses plus the timeouts it does not retry
41
+ # (408 Request Timeout, 504 Gateway Timeout).
42
+ _TEMPORARY_STATUSES = RETRYABLE_STATUSES | {408, 504}
43
+ # Whitespace the Excel can carry around a part number (cells are stored as
44
+ # read): the SQL eligibility filter and the search text strip the same set, so
45
+ # a blank part number never sends an empty search.
46
+ _PART_NUMBER_BLANKS = " \t\r\n\u00a0"
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class CardRecovery:
51
+ """Outcome of one call's part-number recovery."""
52
+
53
+ # Fichas that got a lookup, in request order: each counts against max_items.
54
+ looked_up: tuple[str, ...]
55
+ # Fichas whose own card a lookup returned, recorded like a paged card.
56
+ recovered: tuple[str, ...]
57
+
58
+
59
+ class CardsSyncService:
60
+ """Page search results and persist card observations for stale members."""
61
+
62
+ def __init__(
63
+ self,
64
+ session_factory: sessionmaker[Session],
65
+ client: HttpClient,
66
+ payload_store: PayloadStore,
67
+ *,
68
+ retry_base: timedelta,
69
+ retry_cap: timedelta,
70
+ now: Callable[[], datetime] | None = None,
71
+ ) -> None:
72
+ """``retry_base`` and ``retry_cap`` come from ``Settings.card_lookup_retry_*``."""
73
+ validate_backoff(retry_base, retry_cap)
74
+ self._retry_base = retry_base
75
+ self._retry_cap = retry_cap
76
+ self._session_factory = session_factory
77
+ self._client = client
78
+ self._payload_store = payload_store
79
+ self._now = now or (lambda: datetime.now(UTC))
80
+
81
+ async def sync(self, scope: Mapping[str, ScopeValue], stamp: datetime) -> int:
82
+ """Sync stale member cards under a site stamp and return observation count.
83
+
84
+ When the scope is exactly one category, the first page's filter pane
85
+ also seeds that category's attributes (see ``seed_filter_pane``).
86
+ """
87
+ if stamp.tzinfo is not None:
88
+ raise ValueError("stamp must be a timezone-naive site timestamp")
89
+ scope_values = dict(scope)
90
+ pane_category = _single_category(scope_values)
91
+ conditions = membership_conditions(scope_values)
92
+ with self._session_factory.begin() as session:
93
+ form_scope = _form_scope(
94
+ scope_values,
95
+ _agreement_filters(session, _scope_values(scope_values.get("agreement", ()))),
96
+ )
97
+ member_count = (
98
+ session.scalar(select(func.count(Ficha.ficha_id)).where(*conditions)) or 0
99
+ )
100
+ eligible_ids = list(
101
+ session.scalars(
102
+ select(Ficha.ficha_id)
103
+ .where(*conditions, *_paging_eligible(stamp))
104
+ .order_by(Ficha.ficha_id)
105
+ )
106
+ )
107
+ if not eligible_ids:
108
+ return 0
109
+ # A paging is needed only for fichas no complete paging under the
110
+ # stamp has covered, but every member whose card is unobserved
111
+ # under the stamp takes a card the pages return: a narrower
112
+ # paging that missed it must not make a wider one discard it.
113
+ storable = set(
114
+ session.scalars(
115
+ select(Ficha.ficha_id).where(
116
+ *conditions,
117
+ or_(Ficha.card_stamp.is_(None), Ficha.card_stamp < stamp),
118
+ )
119
+ )
120
+ )
121
+ session.execute(
122
+ update(Ficha).where(*conditions, *_paging_eligible(stamp)).values(card_pending=True)
123
+ )
124
+
125
+ eligible = set(eligible_ids)
126
+ seen: set[str] = set()
127
+ # Fichas whose card a page returned but could not be stored: the
128
+ # paging has found them, so they don't hold it open for more pages.
129
+ returned: set[str] = set()
130
+ observed = 0
131
+ max_pages = math.ceil(member_count / _PAGE_SIZE)
132
+ for page in range(1, max_pages + 1):
133
+ page_form = SearchForm(
134
+ scope=form_scope,
135
+ pagination_page=str(page),
136
+ pagination_left_most_page="1",
137
+ )
138
+ response = await post_search_response(self._client, page_form)
139
+ cards = parse_cards(response.text)
140
+ if page == 1 and not cards:
141
+ # The Excel says the scope has members, so a first page
142
+ # without a card is not the list the site serves (markup
143
+ # drift, an expired session's empty answer): fail the paging
144
+ # instead of recording its fichas as paged.
145
+ raise ParseError("search returned no card on the first page of a non-empty scope")
146
+ if page == 1 and pane_category is not None:
147
+ self._seed_pane(response.text, pane_category, response.extensions["request_id"])
148
+ for card in cards:
149
+ ficha_id = card["ficha_id"]
150
+ if ficha_id not in storable or ficha_id in seen:
151
+ continue
152
+ try:
153
+ self._store_card(card, response.extensions["request_id"], stamp)
154
+ except InvalidExtractionInputError:
155
+ # The ficha's own stored input is unusable: it stays
156
+ # card_pending (left to recovery, which backs it off) and
157
+ # never fails the paging of the others.
158
+ _LOGGER.warning(
159
+ "ficha %s: card not stored, its stored input is unusable",
160
+ ficha_id,
161
+ exc_info=True,
162
+ )
163
+ returned.add(ficha_id)
164
+ continue
165
+ seen.add(ficha_id)
166
+ observed += 1
167
+ if eligible <= seen | returned:
168
+ break
169
+ if len(cards) < _PAGE_SIZE:
170
+ break
171
+ # The paging ran to the end of the scope's list: a ficha it did not
172
+ # return is left to part-number recovery and not paged again under
173
+ # this stamp. An interrupted paging (any exception above) records
174
+ # nothing, so the next sync pages its fichas again.
175
+ missing = sorted(eligible - seen)
176
+ if missing:
177
+ # Chunked to keep each IN list bounded; one transaction, so the
178
+ # paging is recorded all or nothing.
179
+ with self._session_factory.begin() as session:
180
+ for chunk in chunks(missing):
181
+ session.execute(
182
+ update(Ficha)
183
+ .where(Ficha.ficha_id.in_(chunk), *_paging_eligible(stamp))
184
+ .values(card_paged_stamp=stamp)
185
+ .execution_options(synchronize_session=False)
186
+ )
187
+ return observed
188
+
189
+ async def recover(
190
+ self, scope: Mapping[str, ScopeValue], stamp: datetime, max_items: int
191
+ ) -> CardRecovery:
192
+ """Look up member fichas still ``card_pending`` after paging by part number.
193
+
194
+ One ``post_search`` per ficha, least recently tried first (fichas with
195
+ no failed lookup under the stamp first, never looked up first, then by
196
+ the oldest ``card_lookup_stamp``; then failed ones whose backoff has
197
+ passed, longest overdue first; ties by the oldest ``card_stamp``), for at
198
+ most ``max_items`` fichas. Text
199
+ search is fuzzy and site-wide, and only its first page is read, so each
200
+ lookup is filtered to the ficha's own agreement, catalogue and category
201
+ (the form filters :meth:`sync` pages with) for the site to filter before
202
+ ranking; only a returned card whose id is the expected ficha is
203
+ recorded, and any other answer leaves the ficha pending.
204
+
205
+ Each lookup is written ahead as a failed attempt under the stamp
206
+ (``card_lookup_failures`` + 1, ``card_lookup_retry_at`` from the
207
+ exponential backoff), which is also the lease that keeps a concurrent
208
+ recovery off the ficha; a process that dies mid-lookup costs the ficha
209
+ one backoff, never the stamp. Only when the site answered about the
210
+ ficha (a parsed page with its card, recorded, or without it, left
211
+ pending until a newer stamp) is ``card_lookup_stamp`` set to the stamp,
212
+ in the same write that clears the failure record, so later queries
213
+ under the stamp skip it. Only the card with the ficha's id is parsed, so
214
+ a malformed neighbour can't fail the lookup.
215
+
216
+ A failed lookup (an error status that is not temporary, the site's
217
+ error page, an undecodable answer or the ficha's own card unparseable)
218
+ is an error of the attempt, which an expired session or an outage also
219
+ gives: it keeps its attempt, is logged, and the remaining fichas are
220
+ still looked up, unless the lookup before it also failed: then the
221
+ failure is raised (a circuit breaker for a failing site or session; the
222
+ backoff keeps two fichas whose own lookups always fail from tripping it
223
+ on every query and holding back the fichas behind them). A temporary
224
+ failure (a transport error, or a 408, 429, 502, 503 or 504 status,
225
+ after the client's retries) or a returned card that failed to be stored
226
+ also keeps its attempt, and is raised. An interruption (cancellation,
227
+ Ctrl-C), a missing bootstrap or a returned card that could not be
228
+ recorded is not the ficha's failure: the record from before the claim
229
+ is put back, so the next query resumes it. Fichas are looked up least
230
+ recently tried first, so failing ones can't keep the rest out of the
231
+ budget: those beyond the cap are looked up by the next query, and a
232
+ newer stamp makes every pending ficha eligible again.
233
+ """
234
+ if stamp.tzinfo is not None:
235
+ raise ValueError("stamp must be a timezone-naive site timestamp")
236
+ if max_items < 0:
237
+ raise ValueError("max_items must not be negative")
238
+ conditions = membership_conditions(dict(scope))
239
+ if max_items == 0:
240
+ return CardRecovery(looked_up=(), recovered=())
241
+ now = self._now()
242
+ untried = _lookup_untried(stamp)
243
+ eligible = [
244
+ *conditions,
245
+ *_lookup_eligible(stamp),
246
+ # A ficha whose lookup failed under the stamp waits out its backoff.
247
+ or_(untried, Ficha.card_lookup_retry_at.is_(None), Ficha.card_lookup_retry_at <= now),
248
+ ]
249
+ with self._session_factory() as session:
250
+ pending = session.execute(
251
+ select(
252
+ Ficha.ficha_id,
253
+ Ficha.nro_parte,
254
+ Ficha.agreement_id,
255
+ Ficha.catalogue,
256
+ Ficha.category,
257
+ Ficha.card_lookup_stamp,
258
+ Ficha.card_lookup_failure_stamp,
259
+ Ficha.card_lookup_failures,
260
+ Ficha.card_lookup_retry_at,
261
+ )
262
+ .where(*eligible)
263
+ # Least recently tried first: fichas with no failed lookup under
264
+ # the stamp, then a ficha never looked up, then the one looked
265
+ # up longest ago, then failed ones longest overdue first, so
266
+ # fichas whose lookups keep failing can't take the budget from
267
+ # the rest.
268
+ .order_by(
269
+ case((untried, 0), else_=1),
270
+ # NULL for every untried ficha, so it only orders failed
271
+ # ones: longest overdue first.
272
+ case((untried, null()), else_=Ficha.card_lookup_retry_at).asc().nulls_first(),
273
+ Ficha.card_lookup_stamp.asc().nulls_first(),
274
+ Ficha.card_stamp.asc().nulls_first(),
275
+ Ficha.first_seen_at,
276
+ Ficha.ficha_id,
277
+ )
278
+ .limit(max_items)
279
+ ).all()
280
+ filters_by_id = _agreement_filters(
281
+ session, tuple(dict.fromkeys(row.agreement_id for row in pending))
282
+ )
283
+
284
+ looked_up: list[str] = []
285
+ recovered: list[str] = []
286
+ # Circuit breaker: two failed lookups in a row (an error status, the
287
+ # error page, an undecodable answer or an unparseable card) point at the
288
+ # site or the session (an outage, an expired token, a markup change),
289
+ # so the second one stops the recovery. Each failed lookup has already
290
+ # been handed back as a failed attempt with its backoff, so two fichas
291
+ # whose own lookups always fail can't trip it on every query and hold
292
+ # back the fichas behind them.
293
+ failed_in_a_row = 0
294
+ for (
295
+ ficha_id,
296
+ nro_parte,
297
+ agreement_id,
298
+ catalogue,
299
+ category,
300
+ previous_lookup,
301
+ failure_stamp,
302
+ failures,
303
+ retry_at,
304
+ ) in pending:
305
+ before = _LookupRecord(failure_stamp, failures, retry_at)
306
+ claim = self._claim_lookup(ficha_id, stamp, previous_lookup, before, eligible)
307
+ if claim is None:
308
+ # Since the select, another call claimed it or observed its
309
+ # card, it left the scope, or a newer stamp's run recorded a
310
+ # failure for it: no request.
311
+ continue
312
+ part_number = (nro_parte or "").strip(_PART_NUMBER_BLANKS) # never empty: filtered
313
+ ficha_scope: dict[str, ScopeValue] = {"agreement": agreement_id}
314
+ for field, value in (("catalogue", catalogue), ("category", category)):
315
+ if value:
316
+ ficha_scope[field] = value
317
+ form = SearchForm(
318
+ scope=_form_scope(ficha_scope, filters_by_id),
319
+ search_text=part_number,
320
+ search_text_previous=part_number,
321
+ pagination_page="1",
322
+ pagination_left_most_page="1",
323
+ is_new_search=True,
324
+ )
325
+ # The claim is written ahead as a failed attempt with its backoff
326
+ # (also the lease that keeps a concurrent recovery off the ficha),
327
+ # so a process that dies mid-lookup (SIGTERM, SIGKILL, OOM) costs
328
+ # the ficha one backoff, never the stamp. Only when the site
329
+ # answered (a parsed page with the ficha's card, recorded, or
330
+ # without it, left pending until a newer stamp) is the lookup marked
331
+ # done under the stamp, in the same write that clears the failure
332
+ # record. A failed lookup keeps the attempt as written and the other
333
+ # fichas are still looked up: an error status that is not
334
+ # temporary or the site's error page (an error of the attempt,
335
+ # which an expired session or an outage also gives, not an answer
336
+ # about this part number), an answer that could not be decoded, or
337
+ # the ficha's own card unparseable (other cards on the page are not
338
+ # parsed, so a malformed neighbour never fails this lookup). A
339
+ # temporary failure (a transport error, or a 408, 429, 502, 503 or
340
+ # 504 status, after the client's own retries) or a card that failed
341
+ # to be stored also keeps the attempt, and is raised. A
342
+ # precondition such as a missing bootstrap and every interruption
343
+ # (cancelled, Ctrl-C) are not the ficha's: the record before the
344
+ # claim is put back, and they are raised.
345
+ lookup_error: Exception | None = None
346
+ input_error: InvalidExtractionInputError | None = None
347
+ card = None
348
+ recorded = False
349
+ answered = False
350
+ try:
351
+ try:
352
+ response = await post_search_response(self._client, form)
353
+ answered = True
354
+ except httpx2.HTTPStatusError as error:
355
+ if error.response.status_code in _TEMPORARY_STATUSES:
356
+ raise
357
+ lookup_error = error
358
+ except (ParseError, httpx2.DecodingError) as error:
359
+ lookup_error = error
360
+ else:
361
+ try:
362
+ card = parse_card(response.text, ficha_id)
363
+ except ValueError as error: # ParseError included: its card is unparseable
364
+ lookup_error = error
365
+ else:
366
+ if card is not None:
367
+ try:
368
+ recorded = self._store_card(
369
+ card, response.extensions["request_id"], stamp
370
+ )
371
+ except InvalidExtractionInputError as error:
372
+ input_error = error
373
+ except BaseException as error:
374
+ counted = isinstance(error, httpx2.HTTPError) or (
375
+ answered and isinstance(error, Exception)
376
+ )
377
+ if counted:
378
+ _LOGGER.warning(
379
+ "ficha %s: part-number lookup failed (%d in a row under stamp %s); "
380
+ "looked up again from %s: %s",
381
+ ficha_id,
382
+ claim.card_lookup_failures,
383
+ stamp,
384
+ claim.card_lookup_retry_at,
385
+ error,
386
+ )
387
+ else:
388
+ try:
389
+ self._undo_claim(ficha_id, claim, before)
390
+ except Exception:
391
+ # Never replaces the error being raised: the attempt
392
+ # then stays, so the ficha waits out one backoff.
393
+ _LOGGER.exception(
394
+ "ficha %s: could not undo an unfinished part-number lookup", ficha_id
395
+ )
396
+ raise
397
+ looked_up.append(ficha_id)
398
+ if input_error is not None:
399
+ # The site answered, but the ficha's own stored input is
400
+ # unusable: its attempt stays a failure with its backoff. Not a
401
+ # sign of a failing site or session, so it doesn't count
402
+ # toward the circuit breaker.
403
+ _LOGGER.warning(
404
+ "ficha %s: part-number lookup found its card but its stored input is "
405
+ "unusable (%d in a row under stamp %s); looked up again from %s: %s",
406
+ ficha_id,
407
+ claim.card_lookup_failures,
408
+ stamp,
409
+ claim.card_lookup_retry_at,
410
+ input_error,
411
+ )
412
+ continue
413
+ if lookup_error is not None:
414
+ _LOGGER.warning(
415
+ "ficha %s: part-number lookup failed (%d in a row under stamp %s); "
416
+ "looked up again from %s: %s",
417
+ ficha_id,
418
+ claim.card_lookup_failures,
419
+ stamp,
420
+ claim.card_lookup_retry_at,
421
+ lookup_error,
422
+ )
423
+ failed_in_a_row += 1
424
+ if failed_in_a_row >= 2:
425
+ _LOGGER.warning(
426
+ "part-number lookups failed twice in a row under stamp %s; "
427
+ "stopping the recovery: %s",
428
+ stamp,
429
+ lookup_error,
430
+ )
431
+ raise lookup_error
432
+ continue
433
+ failed_in_a_row = 0
434
+ if card is not None and not recorded:
435
+ # The site returned the card, but it could not be recorded (the
436
+ # ficha's input kept changing, or the ficha is gone): hand the
437
+ # ficha back as it was instead of skipping it for the stamp.
438
+ self._undo_claim(ficha_id, claim, before)
439
+ continue
440
+ self._complete_lookup(ficha_id, stamp, claim)
441
+ if card is None:
442
+ _LOGGER.info(
443
+ "ficha %s: part-number search returned no card with its id; left pending",
444
+ ficha_id,
445
+ )
446
+ continue
447
+ recovered.append(ficha_id)
448
+ return CardRecovery(looked_up=tuple(looked_up), recovered=tuple(recovered))
449
+
450
+ def _claim_lookup(
451
+ self,
452
+ ficha_id: str,
453
+ stamp: datetime,
454
+ previous_lookup: datetime | None,
455
+ before: _LookupRecord,
456
+ eligible: Sequence[Any],
457
+ ) -> _LookupRecord | None:
458
+ """Write a part-number lookup ahead as a failed attempt under ``stamp``.
459
+
460
+ Sets the next consecutive failure count under ``stamp`` (from 1 when
461
+ the record is from an older stamp) and ``card_lookup_retry_at`` from the
462
+ backoff, before the request: if the process dies before the site
463
+ answers, the ficha is looked up again once that backoff has passed, and
464
+ until then the retry time keeps a concurrent recovery off it.
465
+ Compare-and-set on the whole predicate the ficha was selected with
466
+ (``eligible``: still a member in scope, still ``card_pending`` with no
467
+ card under the stamp, not looked up under it, out of its backoff), on
468
+ the ``card_lookup_stamp`` and failure record it was selected with, and
469
+ newer stamp only (a record under a newer stamp is never overwritten):
470
+ returns None, so no request is sent, if any of it stopped holding.
471
+ Otherwise returns the record written.
472
+ """
473
+ if (
474
+ before.card_lookup_failure_stamp is not None
475
+ and before.card_lookup_failure_stamp > stamp
476
+ ):
477
+ return None
478
+ same_stamp = before.card_lookup_failure_stamp == stamp
479
+ failures = (before.card_lookup_failures if same_stamp else 0) + 1
480
+ claim = _LookupRecord(
481
+ stamp, failures, self._now() + backoff(failures, self._retry_base, self._retry_cap)
482
+ )
483
+ with self._session_factory.begin() as session:
484
+ result = cast(
485
+ CursorResult[Any],
486
+ session.execute(
487
+ update(Ficha)
488
+ .where(
489
+ Ficha.ficha_id == ficha_id,
490
+ *eligible,
491
+ _equal_or_null(Ficha.card_lookup_stamp, previous_lookup),
492
+ *_record_unchanged(before),
493
+ )
494
+ .values(
495
+ card_lookup_failure_stamp=claim.card_lookup_failure_stamp,
496
+ card_lookup_failures=claim.card_lookup_failures,
497
+ card_lookup_retry_at=claim.card_lookup_retry_at,
498
+ )
499
+ .execution_options(synchronize_session=False)
500
+ ),
501
+ )
502
+ return claim if result.rowcount else None
503
+
504
+ def _complete_lookup(self, ficha_id: str, stamp: datetime, claim: _LookupRecord) -> None:
505
+ """Mark a lookup the site answered as done under ``stamp``.
506
+
507
+ In one write: ``card_lookup_stamp`` = ``stamp`` (newer stamp only), so
508
+ no later query under the stamp repeats it, and the failure record is
509
+ cleared. Compare-and-set on this call's claim, so a record a newer
510
+ stamp's run wrote meanwhile is never touched.
511
+ """
512
+ with self._session_factory.begin() as session:
513
+ session.execute(
514
+ update(Ficha)
515
+ .where(
516
+ Ficha.ficha_id == ficha_id,
517
+ or_(Ficha.card_lookup_stamp.is_(None), Ficha.card_lookup_stamp < stamp),
518
+ *_record_unchanged(claim),
519
+ )
520
+ .values(card_lookup_stamp=stamp, card_lookup_failures=0, card_lookup_retry_at=None)
521
+ .execution_options(synchronize_session=False)
522
+ )
523
+
524
+ def _undo_claim(self, ficha_id: str, claim: _LookupRecord, before: _LookupRecord) -> None:
525
+ """Put back the failure record a claim replaced (the lookup isn't the ficha's failure).
526
+
527
+ Compare-and-set on this call's claim, so a newer write is never undone.
528
+ """
529
+ with self._session_factory.begin() as session:
530
+ session.execute(
531
+ update(Ficha)
532
+ .where(Ficha.ficha_id == ficha_id, *_record_unchanged(claim))
533
+ .values(
534
+ card_lookup_failure_stamp=before.card_lookup_failure_stamp,
535
+ card_lookup_failures=before.card_lookup_failures,
536
+ card_lookup_retry_at=before.card_lookup_retry_at,
537
+ )
538
+ .execution_options(synchronize_session=False)
539
+ )
540
+
541
+ def _seed_pane(self, fragment: str, category: str, request_id: str) -> None:
542
+ pane = parse_filter_pane(fragment)
543
+ with self._session_factory.begin() as session:
544
+ seed_filter_pane(session, pane, category, request_id, self._now())
545
+
546
+ def _store_card(self, card: ParsedCard, request_id: str, stamp: datetime) -> bool:
547
+ """Store one card reading; return whether the ficha now has a card under ``stamp``.
548
+
549
+ False when the ficha row is gone, or when its canonical input kept
550
+ changing so the ficha stays ``card_pending`` (the card row is kept).
551
+ """
552
+ ficha_id = card["ficha_id"]
553
+ observation_key = f"piloto-ai-cli:ficha-card:{ficha_id}:{stamp.isoformat()}"
554
+ card_id = str(uuid5(NAMESPACE_URL, observation_key))
555
+ with self._session_factory.begin() as session:
556
+ if session.get(Ficha, ficha_id) is None:
557
+ return False
558
+
559
+ previous_card = session.execute(
560
+ select(FichaCard.features, FichaCard.stamp)
561
+ .where(FichaCard.ficha_id == ficha_id, FichaCard.card_id != card_id)
562
+ .order_by(
563
+ FichaCard.stamp.desc(),
564
+ FichaCard.observed_at.desc(),
565
+ FichaCard.card_id.desc(),
566
+ )
567
+ .limit(1)
568
+ ).first()
569
+
570
+ upsert(
571
+ session,
572
+ FichaCard,
573
+ [
574
+ {
575
+ "card_id": card_id,
576
+ "ficha_id": ficha_id,
577
+ "request_id": request_id,
578
+ "stamp": stamp,
579
+ "observed_at": self._now(),
580
+ "currency": card["currency"],
581
+ "contracted_min": card["contracted_min"],
582
+ "contracted_max": card["contracted_max"],
583
+ "contracted_avg": card["contracted_avg"],
584
+ "contracted_median": card["contracted_median"],
585
+ "orders_count": card["orders_count"],
586
+ "contracted_amount": card["contracted_amount"],
587
+ "suppliers_count": card["suppliers_count"],
588
+ "entities_count": card["entities_count"],
589
+ "last_sale_date": card["last_sale_date"],
590
+ "offered_min": card["offered_min"],
591
+ "offered_max": card["offered_max"],
592
+ "offered_avg": card["offered_avg"],
593
+ "offered_median": card["offered_median"],
594
+ "offering_suppliers_count": card["offering_suppliers_count"],
595
+ "historico": card["historico"],
596
+ "features": card["features"],
597
+ }
598
+ ],
599
+ )
600
+
601
+ for _ in range(_INPUT_HASH_ATTEMPTS):
602
+ current = session.execute(
603
+ select(Ficha.input_hash, Ficha.card_stamp).where(Ficha.ficha_id == ficha_id)
604
+ ).one()
605
+ if current.card_stamp is not None and current.card_stamp >= stamp:
606
+ return True
607
+ input_hash = current.input_hash
608
+ # The previous card was applied to the current input (its stamp
609
+ # is the ficha's card_stamp; the Excel step also builds the input
610
+ # from the latest card), so unchanged features mean an unchanged
611
+ # input: skip the payload read and write. Otherwise (e.g. an
612
+ # earlier sync lost the input race) rebuild from the input itself.
613
+ features_unchanged = (
614
+ previous_card is not None
615
+ and current.card_stamp is not None
616
+ and previous_card.stamp == current.card_stamp
617
+ and card_features_equal(previous_card.features, card["features"])
618
+ )
619
+ values: dict[str, object] = {"card_stamp": stamp, "card_pending": False}
620
+ if input_hash is not None:
621
+ # The input now holds this card's features (rebuilt below,
622
+ # or already equal): record it as the input's card.
623
+ values["input_card_stamp"] = stamp
624
+ # A ficha without a canonical input yet (e.g. first seen through a
625
+ # department export) only records the observation: the Excel step
626
+ # builds its input from this latest card later.
627
+ if input_hash is not None and not features_unchanged:
628
+ refreshed_hash, size_bytes = rebuild_card_input(
629
+ input_hash, card["features"], self._payload_store
630
+ )
631
+ if refreshed_hash != input_hash:
632
+ self._store_input_payload(session, refreshed_hash, size_bytes)
633
+ values["input_hash"] = refreshed_hash
634
+ # The stored extraction no longer matches the current input.
635
+ values["extraction_pending"] = True
636
+ # Compare-and-set on the hash the new input was built from: another
637
+ # step (Excel, PDF) may have replaced it since it was read.
638
+ result = cast(
639
+ CursorResult[Any],
640
+ session.execute(
641
+ update(Ficha)
642
+ .where(
643
+ Ficha.ficha_id == ficha_id,
644
+ Ficha.input_hash.is_(None)
645
+ if input_hash is None
646
+ else Ficha.input_hash == input_hash,
647
+ or_(Ficha.card_stamp.is_(None), Ficha.card_stamp < stamp),
648
+ )
649
+ .values(values)
650
+ .execution_options(synchronize_session=False)
651
+ ),
652
+ )
653
+ if result.rowcount:
654
+ return True
655
+ # Lost the race every time: the card row is stored, but the ficha
656
+ # keeps card_pending so the next sync refreshes its input. Never stop
657
+ # the whole sync for one ficha.
658
+ _LOGGER.warning("ficha %s: canonical input kept changing; card left pending", ficha_id)
659
+ return False
660
+
661
+ def _store_input_payload(self, session: Session, payload_hash: str, size_bytes: int) -> None:
662
+ upsert(
663
+ session,
664
+ Payload,
665
+ [
666
+ {
667
+ "payload_sha256": payload_hash,
668
+ "content_type": "application/json",
669
+ "size_bytes": size_bytes,
670
+ "storage_uri": self._payload_store.storage_uri(payload_hash),
671
+ "stored_at": self._now(),
672
+ }
673
+ ],
674
+ )
675
+
676
+
677
+ class _LookupRecord(NamedTuple):
678
+ """A ficha's part-number lookup failure record."""
679
+
680
+ card_lookup_failure_stamp: datetime | None
681
+ card_lookup_failures: int
682
+ card_lookup_retry_at: datetime | None
683
+
684
+
685
+ def _equal_or_null(column: Any, value: Any) -> Any:
686
+ return column.is_(None) if value is None else column == value
687
+
688
+
689
+ def _record_unchanged(record: _LookupRecord) -> list[Any]:
690
+ """The ficha's failure record is still ``record`` (compare-and-set)."""
691
+ return [
692
+ _equal_or_null(Ficha.card_lookup_failure_stamp, record.card_lookup_failure_stamp),
693
+ Ficha.card_lookup_failures == record.card_lookup_failures,
694
+ _equal_or_null(Ficha.card_lookup_retry_at, record.card_lookup_retry_at),
695
+ ]
696
+
697
+
698
+ def _paging_eligible(stamp: datetime) -> list[Any]:
699
+ """A ficha whose card paging under ``stamp`` still has to look for.
700
+
701
+ Its card is unobserved under the stamp and no paging of a scope it was
702
+ waiting in has run to the end under the stamp.
703
+ """
704
+ return [
705
+ or_(Ficha.card_stamp.is_(None), Ficha.card_stamp < stamp),
706
+ or_(Ficha.card_paged_stamp.is_(None), Ficha.card_paged_stamp < stamp),
707
+ ]
708
+
709
+
710
+ def card_settled(stamp: datetime) -> Any:
711
+ """The ficha's card needs no further request under ``stamp``.
712
+
713
+ Its card was observed under the stamp, or paging under the stamp did not
714
+ return it and part-number recovery cannot find it under the stamp either:
715
+ the site already answered its lookup, or it has no part number to search
716
+ for. A ficha whose lookup failed (backoff) or is still untried is not
717
+ settled. The sync shortcut and the card-paging gate both rest on this, so
718
+ a card the site never returns costs its requests once per stamp, never
719
+ once per query. Two-valued in SQL (no NULL result), so it can be negated.
720
+ """
721
+ return or_(
722
+ and_(Ficha.card_stamp.is_not(None), Ficha.card_stamp >= stamp),
723
+ and_(
724
+ Ficha.card_paged_stamp.is_not(None),
725
+ Ficha.card_paged_stamp >= stamp,
726
+ or_(
727
+ and_(Ficha.card_lookup_stamp.is_not(None), Ficha.card_lookup_stamp >= stamp),
728
+ Ficha.nro_parte.is_(None),
729
+ func.trim(Ficha.nro_parte, _PART_NUMBER_BLANKS) == "",
730
+ ),
731
+ ),
732
+ )
733
+
734
+
735
+ def _lookup_eligible(stamp: datetime) -> list[Any]:
736
+ """A ficha that still needs a part-number lookup under ``stamp``."""
737
+ return [
738
+ Ficha.card_pending,
739
+ or_(Ficha.card_stamp.is_(None), Ficha.card_stamp < stamp),
740
+ or_(Ficha.card_lookup_stamp.is_(None), Ficha.card_lookup_stamp < stamp),
741
+ # Without a part number there is nothing to search for: the ficha
742
+ # stays pending and costs no request.
743
+ Ficha.nro_parte.is_not(None),
744
+ func.trim(Ficha.nro_parte, _PART_NUMBER_BLANKS) != "",
745
+ ]
746
+
747
+
748
+ def _lookup_untried(stamp: datetime) -> Any:
749
+ """No failed part-number lookup recorded for the ficha under ``stamp``.
750
+
751
+ Never failed, its last lookup completed, or its failures were under an
752
+ older stamp.
753
+ """
754
+ return or_(
755
+ Ficha.card_lookup_failures == 0,
756
+ Ficha.card_lookup_failure_stamp.is_(None),
757
+ Ficha.card_lookup_failure_stamp < stamp,
758
+ )
759
+
760
+
761
+ def _agreement_filters(session: Session, agreement_ids: Sequence[str]) -> dict[str, str]:
762
+ """Map agreement ids to the ``filter_value`` the site expects in its form."""
763
+ if not agreement_ids:
764
+ return {}
765
+ rows = session.execute(
766
+ select(Agreement.agreement_id, Agreement.filter_value).where(
767
+ Agreement.agreement_id.in_(agreement_ids)
768
+ )
769
+ ).all()
770
+ filters_by_id = {agreement_id: filter_value for agreement_id, filter_value in rows}
771
+ if set(filters_by_id) != set(agreement_ids):
772
+ raise ValueError("search scope contains an unknown agreement id")
773
+ return filters_by_id
774
+
775
+
776
+ def _form_scope(
777
+ scope: Mapping[str, ScopeValue], filters_by_id: Mapping[str, str]
778
+ ) -> dict[str, ScopeValue]:
779
+ """Translate a structural scope into search form filters.
780
+
781
+ Agreement ids become their ``filter_value`` (see :func:`_agreement_filters`);
782
+ catalogue, category and department values are sent as they are.
783
+ """
784
+ form_scope = dict(scope)
785
+ if "agreement" in scope:
786
+ filter_values = tuple(
787
+ filters_by_id[agreement_id] for agreement_id in _scope_values(scope["agreement"])
788
+ )
789
+ form_scope["agreement"] = (
790
+ filter_values[0] if isinstance(scope["agreement"], str) else filter_values
791
+ )
792
+ return form_scope
793
+
794
+
795
+ def _scope_values(value: ScopeValue) -> tuple[str, ...]:
796
+ return (value,) if isinstance(value, str) else tuple(value)
797
+
798
+
799
+ def _single_category(scope: Mapping[str, ScopeValue]) -> str | None:
800
+ """The scope's category when it is exactly one; a wider pane is not seeded.
801
+
802
+ A pane over several categories (or a scope without a category, e.g. an
803
+ agreement) doesn't say which category each value belongs to.
804
+ """
805
+ categories = set(_scope_values(scope.get("category", ())))
806
+ if len(categories) != 1:
807
+ return None
808
+ (category,) = categories
809
+ return category if category.strip() else None
810
+
811
+
812
+ def _equal_or_in(column: Any, values: Sequence[str]) -> Any:
813
+ return column == values[0] if len(values) == 1 else column.in_(values)
814
+
815
+
816
+ def membership_conditions(scope: Mapping[str, ScopeValue]) -> list[Any]:
817
+ """Conditions on ``Ficha`` selecting the scope's current member fichas.
818
+
819
+ Department membership (``v_department_ficha``) when the scope has a
820
+ department, else agreement-wide membership (``v_member_ficha``), narrowed
821
+ by the scope's agreement, catalogue and category.
822
+ """
823
+ department_values = _scope_values(scope.get("department", ()))
824
+ conditions: list[Any] = []
825
+ if not department_values:
826
+ # Agreement-wide membership (v_member_ficha). A department scope uses
827
+ # department membership instead (v_department_ficha): a ficha first seen
828
+ # through a department export has no agreement-wide excel_stamp yet.
829
+ conditions.append(
830
+ exists(
831
+ select(1)
832
+ .select_from(Agreement)
833
+ .where(
834
+ Agreement.agreement_id == Ficha.agreement_id,
835
+ Agreement.excel_stamp == Ficha.excel_stamp,
836
+ )
837
+ )
838
+ )
839
+ for field, column in (
840
+ ("agreement", Ficha.agreement_id),
841
+ ("catalogue", Ficha.catalogue),
842
+ ("category", Ficha.category),
843
+ ):
844
+ if field in scope:
845
+ values = _scope_values(scope[field])
846
+ if values:
847
+ conditions.append(_equal_or_in(column, values))
848
+
849
+ if department_values:
850
+ agreement_values = _scope_values(scope.get("agreement", ()))
851
+ if not agreement_values or not all(value.strip() for value in agreement_values):
852
+ raise ValueError("department scope requires an agreement")
853
+ conditions.append(
854
+ exists(
855
+ select(1)
856
+ .select_from(FichaDepartment)
857
+ .join(
858
+ DepartmentSync,
859
+ and_(
860
+ DepartmentSync.agreement_id == Ficha.agreement_id,
861
+ DepartmentSync.department == FichaDepartment.department,
862
+ DepartmentSync.excel_stamp == FichaDepartment.stamp,
863
+ ),
864
+ )
865
+ .where(
866
+ FichaDepartment.ficha_id == Ficha.ficha_id,
867
+ FichaDepartment.department.in_(department_values),
868
+ )
869
+ )
870
+ )
871
+ return conditions