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.
- perucompras_cli-0.1.0.dist-info/METADATA +429 -0
- perucompras_cli-0.1.0.dist-info/RECORD +50 -0
- perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
- perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
- perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
- piloto_ai_cli/__init__.py +51 -0
- piloto_ai_cli/__main__.py +5 -0
- piloto_ai_cli/api.py +394 -0
- piloto_ai_cli/attribute_text.py +106 -0
- piloto_ai_cli/attributes_service.py +250 -0
- piloto_ai_cli/auto_tag.py +65 -0
- piloto_ai_cli/backoff.py +25 -0
- piloto_ai_cli/cards.py +871 -0
- piloto_ai_cli/cli.py +602 -0
- piloto_ai_cli/connectors.py +106 -0
- piloto_ai_cli/database.py +491 -0
- piloto_ai_cli/enrichment.py +557 -0
- piloto_ai_cli/errors.py +92 -0
- piloto_ai_cli/excel.py +186 -0
- piloto_ai_cli/extraction.py +1316 -0
- piloto_ai_cli/health.py +398 -0
- piloto_ai_cli/health_workflow.py +1060 -0
- piloto_ai_cli/http_client.py +610 -0
- piloto_ai_cli/llm_client.py +259 -0
- piloto_ai_cli/llm_extraction.py +444 -0
- piloto_ai_cli/llm_output.py +90 -0
- piloto_ai_cli/pane.py +303 -0
- piloto_ai_cli/parsers.py +477 -0
- piloto_ai_cli/payload_store.py +227 -0
- piloto_ai_cli/pdf_parser.py +12 -0
- piloto_ai_cli/py.typed +0 -0
- piloto_ai_cli/query_compiler.py +1112 -0
- piloto_ai_cli/query_result.py +175 -0
- piloto_ai_cli/query_service.py +199 -0
- piloto_ai_cli/reextract.py +129 -0
- piloto_ai_cli/review.py +217 -0
- piloto_ai_cli/rules.py +67 -0
- piloto_ai_cli/run_log.py +230 -0
- piloto_ai_cli/schema/__init__.py +25 -0
- piloto_ai_cli/schema/contract-v1.schema.json +261 -0
- piloto_ai_cli/schema/contract.py +257 -0
- piloto_ai_cli/schema/migration_filters.py +59 -0
- piloto_ai_cli/schema/models.py +747 -0
- piloto_ai_cli/schema/snowflake_autogen.py +134 -0
- piloto_ai_cli/search_form.py +82 -0
- piloto_ai_cli/settings.py +174 -0
- piloto_ai_cli/snowflake_url.py +90 -0
- piloto_ai_cli/stamp_service.py +53 -0
- piloto_ai_cli/sync.py +1157 -0
- piloto_ai_cli/unit_converter.py +81 -0
piloto_ai_cli/sync.py
ADDED
|
@@ -0,0 +1,1157 @@
|
|
|
1
|
+
"""Bring a query's scope up to the site stamp (``SyncService.sync``).
|
|
2
|
+
|
|
3
|
+
The Excel steps (agreement and department exports) live here; ``sync`` composes
|
|
4
|
+
them with the card, part-number recovery, rules-pass and enrichment steps
|
|
5
|
+
(data-model.md §4, ``SyncService.sync(scope, needs, max_items)``).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import hashlib
|
|
10
|
+
import logging
|
|
11
|
+
import threading
|
|
12
|
+
from collections.abc import (
|
|
13
|
+
Callable,
|
|
14
|
+
Collection,
|
|
15
|
+
Coroutine,
|
|
16
|
+
Iterable,
|
|
17
|
+
Iterator,
|
|
18
|
+
Mapping,
|
|
19
|
+
Sequence,
|
|
20
|
+
)
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from datetime import UTC, datetime, timedelta
|
|
23
|
+
from typing import Any, cast
|
|
24
|
+
|
|
25
|
+
import httpx2
|
|
26
|
+
from sqlalchemy import exists, func, or_, select, update
|
|
27
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
28
|
+
|
|
29
|
+
from piloto_ai_cli.cards import CardRecovery, CardsSyncService, card_settled, membership_conditions
|
|
30
|
+
from piloto_ai_cli.connectors import HOME_URL, post_download_response
|
|
31
|
+
from piloto_ai_cli.database import chunks, upsert
|
|
32
|
+
from piloto_ai_cli.enrichment import Enrichment, EnrichmentService
|
|
33
|
+
from piloto_ai_cli.errors import ContractError, ContractErrorCode, InvalidExtractionInputError
|
|
34
|
+
from piloto_ai_cli.excel import ExcelFicha, parse_excel
|
|
35
|
+
from piloto_ai_cli.extraction import ExtractService, canonical_extraction_input
|
|
36
|
+
from piloto_ai_cli.http_client import HttpClient
|
|
37
|
+
from piloto_ai_cli.parsers import Feature
|
|
38
|
+
from piloto_ai_cli.payload_store import PayloadStore
|
|
39
|
+
from piloto_ai_cli.schema.contract import STRUCTURAL_FIELDS, ValidatedContract
|
|
40
|
+
from piloto_ai_cli.schema.models import (
|
|
41
|
+
Agreement,
|
|
42
|
+
Attribute,
|
|
43
|
+
AttributeScope,
|
|
44
|
+
DepartmentSync,
|
|
45
|
+
Extraction,
|
|
46
|
+
Ficha,
|
|
47
|
+
FichaCard,
|
|
48
|
+
FichaDepartment,
|
|
49
|
+
Payload,
|
|
50
|
+
Pdf,
|
|
51
|
+
)
|
|
52
|
+
from piloto_ai_cli.search_form import SearchForm
|
|
53
|
+
|
|
54
|
+
_LOGGER = logging.getLogger(__name__)
|
|
55
|
+
|
|
56
|
+
_SYNC_LOCKS_GUARD = threading.Lock()
|
|
57
|
+
_SYNC_LOCKS: dict[tuple[str, str | None], threading.Lock] = {}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _sync_lock(agreement_id: str, department: str | None = None) -> threading.Lock:
|
|
61
|
+
with _SYNC_LOCKS_GUARD:
|
|
62
|
+
return _SYNC_LOCKS.setdefault((agreement_id, department), threading.Lock())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def _acquire(lock: threading.Lock) -> None:
|
|
66
|
+
while not lock.acquire(blocking=False):
|
|
67
|
+
await asyncio.sleep(0.01)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True, slots=True)
|
|
71
|
+
class SyncSteps:
|
|
72
|
+
"""The run's collaborators that :meth:`SyncService.sync` composes.
|
|
73
|
+
|
|
74
|
+
``cards`` and ``enrichment`` send their requests through ``client``, the
|
|
75
|
+
run's bootstrapped client (``StampService.read()`` bootstraps it).
|
|
76
|
+
``extractor`` builds the ``ExtractService`` the rules pass runs with.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
client: HttpClient
|
|
80
|
+
cards: CardsSyncService
|
|
81
|
+
enrichment: EnrichmentService
|
|
82
|
+
extractor: Callable[[Session], ExtractService]
|
|
83
|
+
base_url: str = HOME_URL
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True, slots=True)
|
|
87
|
+
class SyncResult:
|
|
88
|
+
"""What one :meth:`SyncService.sync` call did.
|
|
89
|
+
|
|
90
|
+
``shortcut`` is True when the scope was already current and needed nothing:
|
|
91
|
+
then no step ran and no request was made. ``excel_applied`` says whether
|
|
92
|
+
an export (agreement or department) was applied; ``rules_passed`` are the
|
|
93
|
+
member fichas whose new input got its rules pass.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
shortcut: bool
|
|
97
|
+
needs: frozenset[str]
|
|
98
|
+
excel_applied: bool = False
|
|
99
|
+
cards_observed: int = 0
|
|
100
|
+
recovery: CardRecovery = field(default_factory=lambda: CardRecovery((), ()))
|
|
101
|
+
rules_passed: tuple[str, ...] = ()
|
|
102
|
+
enrichment: Enrichment = field(default_factory=lambda: Enrichment((), (), 0))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def require_agreement(contract: ValidatedContract) -> str:
|
|
106
|
+
"""Return the scope's agreement, refusing a scope without one.
|
|
107
|
+
|
|
108
|
+
The refusal is a ``ContractError`` on ``scope.agreement``.
|
|
109
|
+
|
|
110
|
+
The Excel export, the source of a scope's membership, is per agreement: a
|
|
111
|
+
scope without one could never be brought current (decided 2026-11-23, PR
|
|
112
|
+
#178, option A). The check needs only the document, so callers run it
|
|
113
|
+
before any request.
|
|
114
|
+
"""
|
|
115
|
+
scope = contract.scope
|
|
116
|
+
agreement_id = scope.get("agreement")
|
|
117
|
+
if agreement_id is None:
|
|
118
|
+
raise ContractError(
|
|
119
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
120
|
+
"scope.agreement",
|
|
121
|
+
"Department scope requires an agreement."
|
|
122
|
+
if scope.get("department") is not None
|
|
123
|
+
else "A query scope requires an agreement: the catalogue is synced per agreement.",
|
|
124
|
+
)
|
|
125
|
+
return agreement_id
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class SyncService:
|
|
129
|
+
"""Bring a scope up to the stamp: Excel, cards, then enrichment where needed."""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
session_factory: sessionmaker[Session],
|
|
134
|
+
payload_store: PayloadStore,
|
|
135
|
+
*,
|
|
136
|
+
now: Callable[[], datetime] | None = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
self._session_factory = session_factory
|
|
139
|
+
self._payload_store = payload_store
|
|
140
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
141
|
+
|
|
142
|
+
async def sync(
|
|
143
|
+
self,
|
|
144
|
+
contract: ValidatedContract,
|
|
145
|
+
max_items: int,
|
|
146
|
+
*,
|
|
147
|
+
stamp: datetime,
|
|
148
|
+
steps: SyncSteps,
|
|
149
|
+
) -> SyncResult:
|
|
150
|
+
"""Bring the contract's scope up to ``stamp`` for this query (data-model.md §4).
|
|
151
|
+
|
|
152
|
+
The scope is ``contract.scope``; ``needs`` are derived from the
|
|
153
|
+
contract's predicates and facets (:func:`query_needs`). The shortcut:
|
|
154
|
+
when the scope's list is current under the stamp (the agreement
|
|
155
|
+
checkpoint, or the ``department_sync`` row when the scope has a
|
|
156
|
+
department; a missing row is never current), every member ficha's card
|
|
157
|
+
is settled under the stamp (observed, or not returned by a complete
|
|
158
|
+
paging and its part-number lookup already answered or impossible; see
|
|
159
|
+
:func:`~piloto_ai_cli.cards.card_settled`), no member's input
|
|
160
|
+
awaits its rules pass, and every needed attribute is resolved, nothing
|
|
161
|
+
runs and no request is made.
|
|
162
|
+
|
|
163
|
+
Otherwise the steps run in order, each gated on its own freshness so a
|
|
164
|
+
current step makes no request: the Excel export (the department's list
|
|
165
|
+
when the scope has a department, else the agreement's), card
|
|
166
|
+
paging of the fichas no complete paging has covered under the stamp
|
|
167
|
+
(which seeds a one-category scope's filter pane from its first page),
|
|
168
|
+
part-number recovery of fichas still ``card_pending``, the rules pass
|
|
169
|
+
for every member with a new input (no request), then enrichment
|
|
170
|
+
(PDF, rules, LLM) of the fichas the query still needs. ``max_items``
|
|
171
|
+
counts fichas across recovery and enrichment: at most that many
|
|
172
|
+
distinct fichas get per-ficha work, and the rest stay pending for the
|
|
173
|
+
next query. Each step writes per-ficha state as each ficha finishes, so
|
|
174
|
+
an interruption leaves exactly the unfinished fichas pending.
|
|
175
|
+
|
|
176
|
+
A scope without an agreement (the export, the source of membership,
|
|
177
|
+
is per agreement) and an unknown agreement are refused with a
|
|
178
|
+
``ContractError`` on ``scope.agreement`` before any request.
|
|
179
|
+
"""
|
|
180
|
+
if stamp.tzinfo is not None:
|
|
181
|
+
raise ValueError("stamp must be a naive Lima-time datetime")
|
|
182
|
+
if max_items < 0:
|
|
183
|
+
raise ValueError("max_items must not be negative")
|
|
184
|
+
scope = contract.scope
|
|
185
|
+
agreement_id = require_agreement(contract)
|
|
186
|
+
department = scope.get("department")
|
|
187
|
+
with self._session_factory() as session:
|
|
188
|
+
if agreement_id is not None and session.get(Agreement, agreement_id) is None:
|
|
189
|
+
raise ContractError(
|
|
190
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
191
|
+
"scope.agreement",
|
|
192
|
+
f"Unknown agreement: {agreement_id}",
|
|
193
|
+
)
|
|
194
|
+
needs = query_needs(session, contract)
|
|
195
|
+
current = _list_current(session, scope, stamp) and not _member_work_pending(
|
|
196
|
+
session, scope, stamp
|
|
197
|
+
)
|
|
198
|
+
if current and steps.enrichment.needs_resolved(contract, needs):
|
|
199
|
+
return SyncResult(shortcut=True, needs=needs)
|
|
200
|
+
|
|
201
|
+
if department is not None:
|
|
202
|
+
excel_applied = await self.sync_department(
|
|
203
|
+
agreement_id, department, stamp, steps.client, steps.base_url
|
|
204
|
+
)
|
|
205
|
+
else:
|
|
206
|
+
excel_applied = await self.sync_agreement(
|
|
207
|
+
agreement_id, stamp, steps.client, steps.base_url
|
|
208
|
+
)
|
|
209
|
+
cards_observed = await steps.cards.sync(scope, stamp)
|
|
210
|
+
recovery = await steps.cards.recover(scope, stamp, max_items)
|
|
211
|
+
stop = threading.Event()
|
|
212
|
+
rules_passed = await _run_until_stopped(
|
|
213
|
+
asyncio.to_thread(
|
|
214
|
+
self._rules_pass_new_inputs,
|
|
215
|
+
scope,
|
|
216
|
+
steps.extractor,
|
|
217
|
+
steps.enrichment.retry_after,
|
|
218
|
+
stop,
|
|
219
|
+
),
|
|
220
|
+
stop,
|
|
221
|
+
)
|
|
222
|
+
# Re-derived: the pane the card step seeded may have added applicable
|
|
223
|
+
# attributes that ``facets: "all"`` needs.
|
|
224
|
+
with self._session_factory() as session:
|
|
225
|
+
needs = query_needs(session, contract)
|
|
226
|
+
enrichment = await steps.enrichment.enrich(
|
|
227
|
+
contract, needs, max_items, counted=recovery.looked_up
|
|
228
|
+
)
|
|
229
|
+
return SyncResult(
|
|
230
|
+
shortcut=False,
|
|
231
|
+
needs=needs,
|
|
232
|
+
excel_applied=excel_applied,
|
|
233
|
+
cards_observed=cards_observed,
|
|
234
|
+
recovery=recovery,
|
|
235
|
+
rules_passed=rules_passed,
|
|
236
|
+
enrichment=enrichment,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
def _rules_pass_new_inputs(
|
|
240
|
+
self,
|
|
241
|
+
scope: Mapping[str, str],
|
|
242
|
+
extractor: Callable[[Session], ExtractService],
|
|
243
|
+
retry_after: Callable[[int], timedelta],
|
|
244
|
+
stop: threading.Event,
|
|
245
|
+
) -> tuple[str, ...]:
|
|
246
|
+
"""Run the rules pass for every member ficha whose input has none yet.
|
|
247
|
+
|
|
248
|
+
No request. Oldest first, one transaction per ficha, so an
|
|
249
|
+
interruption leaves exactly the fichas not yet passed. A pass that
|
|
250
|
+
leaves no residue finishes the ficha's extraction for that input
|
|
251
|
+
(``extraction_pending`` cleared, compare-and-set on the input hash);
|
|
252
|
+
otherwise the residue waits for the query-driven LLM pass.
|
|
253
|
+
|
|
254
|
+
A pass that fails because the ficha's own stored input is corrupt or
|
|
255
|
+
invalid (``InvalidExtractionInputError``) is logged and
|
|
256
|
+
recorded on the ficha (``rules_failures`` for that input,
|
|
257
|
+
``rules_retry_at`` from ``retry_after``) and the next ficha is passed:
|
|
258
|
+
one failing ficha never fails the query or holds back the rest.
|
|
259
|
+
A ficha still in its backoff for its current input is skipped; it keeps
|
|
260
|
+
awaiting its rules pass, so the scope is not current until it passes.
|
|
261
|
+
Any other error (configuration, storage, database, a bug) propagates.
|
|
262
|
+
"""
|
|
263
|
+
now = self._now()
|
|
264
|
+
with self._session_factory() as session:
|
|
265
|
+
ficha_ids = session.scalars(
|
|
266
|
+
select(Ficha.ficha_id)
|
|
267
|
+
.where(
|
|
268
|
+
*membership_conditions(scope),
|
|
269
|
+
_awaits_rules_pass(),
|
|
270
|
+
_rules_pass_due(now),
|
|
271
|
+
)
|
|
272
|
+
.order_by(Ficha.first_seen_at, Ficha.ficha_id)
|
|
273
|
+
).all()
|
|
274
|
+
passed: list[str] = []
|
|
275
|
+
for ficha_id in ficha_ids:
|
|
276
|
+
if stop.is_set():
|
|
277
|
+
# Cancelled: stop after the ficha in progress committed, so
|
|
278
|
+
# the rest still await their pass.
|
|
279
|
+
break
|
|
280
|
+
with self._session_factory() as session:
|
|
281
|
+
ficha = session.get(Ficha, ficha_id)
|
|
282
|
+
if ficha is None or ficha.input_hash is None:
|
|
283
|
+
continue
|
|
284
|
+
input_hash = ficha.input_hash
|
|
285
|
+
# Built outside the per-ficha handler: a configuration error is
|
|
286
|
+
# not this ficha's failure and must fail the sync.
|
|
287
|
+
service = extractor(session)
|
|
288
|
+
try:
|
|
289
|
+
result = service.rules_pass(ficha)
|
|
290
|
+
session.execute(
|
|
291
|
+
update(Ficha)
|
|
292
|
+
.where(
|
|
293
|
+
Ficha.ficha_id == ficha_id,
|
|
294
|
+
Ficha.input_hash == result.input_hash,
|
|
295
|
+
)
|
|
296
|
+
.values(
|
|
297
|
+
rules_failed_input_hash=None,
|
|
298
|
+
rules_failures=0,
|
|
299
|
+
rules_retry_at=None,
|
|
300
|
+
**({} if result.residue else {"extraction_pending": False}),
|
|
301
|
+
)
|
|
302
|
+
.execution_options(synchronize_session=False)
|
|
303
|
+
)
|
|
304
|
+
session.commit()
|
|
305
|
+
except InvalidExtractionInputError:
|
|
306
|
+
# Only the ficha's own input failing is isolated; storage,
|
|
307
|
+
# database and programming errors propagate (fail fast).
|
|
308
|
+
session.rollback()
|
|
309
|
+
failures = self._record_rules_failure(ficha_id, input_hash, retry_after)
|
|
310
|
+
if failures == 0:
|
|
311
|
+
_LOGGER.warning(
|
|
312
|
+
"ficha %s: rules pass failed for superseded input %s; "
|
|
313
|
+
"the new input is tried at once",
|
|
314
|
+
ficha_id,
|
|
315
|
+
input_hash,
|
|
316
|
+
exc_info=True,
|
|
317
|
+
)
|
|
318
|
+
else:
|
|
319
|
+
_LOGGER.warning(
|
|
320
|
+
"ficha %s: rules pass failed (%d in a row for input %s); "
|
|
321
|
+
"retried after %s",
|
|
322
|
+
ficha_id,
|
|
323
|
+
failures,
|
|
324
|
+
input_hash,
|
|
325
|
+
retry_after(failures),
|
|
326
|
+
exc_info=True,
|
|
327
|
+
)
|
|
328
|
+
continue
|
|
329
|
+
passed.append(ficha_id)
|
|
330
|
+
return tuple(passed)
|
|
331
|
+
|
|
332
|
+
def _record_rules_failure(
|
|
333
|
+
self, ficha_id: str, input_hash: str, retry_after: Callable[[int], timedelta]
|
|
334
|
+
) -> int:
|
|
335
|
+
"""Record a failed rules pass for ``input_hash``; return the consecutive failures.
|
|
336
|
+
|
|
337
|
+
Compare-and-set on the input: if another step replaced it meanwhile,
|
|
338
|
+
nothing is recorded (the new input is tried at once) and 0 is returned.
|
|
339
|
+
"""
|
|
340
|
+
with self._session_factory.begin() as session:
|
|
341
|
+
current = session.execute(
|
|
342
|
+
select(Ficha.rules_failed_input_hash, Ficha.rules_failures).where(
|
|
343
|
+
Ficha.ficha_id == ficha_id, Ficha.input_hash == input_hash
|
|
344
|
+
)
|
|
345
|
+
).one_or_none()
|
|
346
|
+
if current is None:
|
|
347
|
+
return 0
|
|
348
|
+
same_input = current.rules_failed_input_hash == input_hash
|
|
349
|
+
failures = (current.rules_failures if same_input else 0) + 1
|
|
350
|
+
session.execute(
|
|
351
|
+
update(Ficha)
|
|
352
|
+
.where(Ficha.ficha_id == ficha_id, Ficha.input_hash == input_hash)
|
|
353
|
+
.values(
|
|
354
|
+
rules_failed_input_hash=input_hash,
|
|
355
|
+
rules_failures=failures,
|
|
356
|
+
rules_retry_at=self._now() + retry_after(failures),
|
|
357
|
+
)
|
|
358
|
+
.execution_options(synchronize_session=False)
|
|
359
|
+
)
|
|
360
|
+
return failures
|
|
361
|
+
|
|
362
|
+
async def sync_agreement(
|
|
363
|
+
self,
|
|
364
|
+
agreement_id: str,
|
|
365
|
+
stamp: datetime,
|
|
366
|
+
client: HttpClient,
|
|
367
|
+
base_url: str,
|
|
368
|
+
) -> bool:
|
|
369
|
+
"""Download and atomically apply a complete export if its stamp is newer.
|
|
370
|
+
|
|
371
|
+
``stamp`` is the site's naive Lima-time stamp (stored as TIMESTAMP_NTZ);
|
|
372
|
+
a timezone-aware value is rejected before anything is downloaded.
|
|
373
|
+
"""
|
|
374
|
+
if stamp.tzinfo is not None:
|
|
375
|
+
raise ValueError("stamp must be a naive Lima-time datetime")
|
|
376
|
+
# One sync per agreement at a time in this process, from the freshness
|
|
377
|
+
# check through the apply: a second sync of the same stamp then sees the
|
|
378
|
+
# new checkpoint and makes no request. Cross-process races are still
|
|
379
|
+
# settled by the excel_stamp guard in ``_apply``.
|
|
380
|
+
lock = _sync_lock(agreement_id)
|
|
381
|
+
await _acquire(lock)
|
|
382
|
+
try:
|
|
383
|
+
return await self._sync_agreement_locked(agreement_id, stamp, client, base_url)
|
|
384
|
+
finally:
|
|
385
|
+
lock.release()
|
|
386
|
+
|
|
387
|
+
async def _sync_agreement_locked(
|
|
388
|
+
self,
|
|
389
|
+
agreement_id: str,
|
|
390
|
+
stamp: datetime,
|
|
391
|
+
client: HttpClient,
|
|
392
|
+
base_url: str,
|
|
393
|
+
) -> bool:
|
|
394
|
+
with self._session_factory() as session:
|
|
395
|
+
agreement = session.get(Agreement, agreement_id)
|
|
396
|
+
if agreement is None:
|
|
397
|
+
raise ValueError(f"Unknown agreement: {agreement_id}")
|
|
398
|
+
if agreement.excel_stamp is not None and agreement.excel_stamp >= stamp:
|
|
399
|
+
return False
|
|
400
|
+
agreement_filter = agreement.filter_value
|
|
401
|
+
expected_count = agreement.ficha_count
|
|
402
|
+
|
|
403
|
+
content, request_id = await _download(
|
|
404
|
+
client, base_url, SearchForm(scope={"agreement": agreement_filter})
|
|
405
|
+
)
|
|
406
|
+
# Parsing the workbook is CPU-bound and the apply step does payload-store
|
|
407
|
+
# I/O and database writes: run both off the event loop so other
|
|
408
|
+
# coroutines (and request logging) keep going.
|
|
409
|
+
return await _run_apply(
|
|
410
|
+
asyncio.to_thread(
|
|
411
|
+
self._parse_and_apply,
|
|
412
|
+
agreement_id,
|
|
413
|
+
stamp,
|
|
414
|
+
content,
|
|
415
|
+
expected_count,
|
|
416
|
+
request_id,
|
|
417
|
+
)
|
|
418
|
+
)
|
|
419
|
+
|
|
420
|
+
async def sync_department(
|
|
421
|
+
self,
|
|
422
|
+
agreement_id: str,
|
|
423
|
+
department: str,
|
|
424
|
+
stamp: datetime,
|
|
425
|
+
client: HttpClient,
|
|
426
|
+
base_url: str,
|
|
427
|
+
) -> bool:
|
|
428
|
+
"""Download and atomically apply a department's complete list if its stamp is newer.
|
|
429
|
+
|
|
430
|
+
Always the full (agreement, department) list, never narrowed by
|
|
431
|
+
catalogue or category. Returns whether this export was applied. When the
|
|
432
|
+
download fails (site down, timeout, error page, invalid workbook)
|
|
433
|
+
nothing is written: if the pair was synced before, the last complete
|
|
434
|
+
list stands and ``False`` is returned; if it never was, a
|
|
435
|
+
``department_unavailable`` contract error is raised, since every ficha's
|
|
436
|
+
availability there is unknown.
|
|
437
|
+
"""
|
|
438
|
+
if stamp.tzinfo is not None:
|
|
439
|
+
raise ValueError("stamp must be a naive Lima-time datetime")
|
|
440
|
+
if not department.strip():
|
|
441
|
+
raise ValueError("department cannot be empty")
|
|
442
|
+
lock = _sync_lock(agreement_id, department)
|
|
443
|
+
await _acquire(lock)
|
|
444
|
+
try:
|
|
445
|
+
return await self._sync_department_locked(
|
|
446
|
+
agreement_id, department, stamp, client, base_url
|
|
447
|
+
)
|
|
448
|
+
finally:
|
|
449
|
+
lock.release()
|
|
450
|
+
|
|
451
|
+
async def _sync_department_locked(
|
|
452
|
+
self,
|
|
453
|
+
agreement_id: str,
|
|
454
|
+
department: str,
|
|
455
|
+
stamp: datetime,
|
|
456
|
+
client: HttpClient,
|
|
457
|
+
base_url: str,
|
|
458
|
+
) -> bool:
|
|
459
|
+
with self._session_factory() as session:
|
|
460
|
+
agreement = session.get(Agreement, agreement_id)
|
|
461
|
+
if agreement is None:
|
|
462
|
+
raise ValueError(f"Unknown agreement: {agreement_id}")
|
|
463
|
+
checkpoint = session.get(DepartmentSync, (agreement_id, department))
|
|
464
|
+
if checkpoint is not None and checkpoint.excel_stamp >= stamp:
|
|
465
|
+
return False
|
|
466
|
+
agreement_filter = agreement.filter_value
|
|
467
|
+
|
|
468
|
+
form = SearchForm(scope={"agreement": agreement_filter, "department": department})
|
|
469
|
+
# Only a failed download counts as the site being unavailable: an HTTP
|
|
470
|
+
# error status, a transport error or timeout, the error page, or an
|
|
471
|
+
# invalid workbook. Precondition errors raised before any request (no
|
|
472
|
+
# bootstrap token, a malformed form) are caller bugs and propagate.
|
|
473
|
+
failure: Exception | None = None
|
|
474
|
+
try:
|
|
475
|
+
content, request_id = await _download(client, base_url, form)
|
|
476
|
+
except (httpx2.HTTPError, _ErrorPageError) as error:
|
|
477
|
+
failure = error
|
|
478
|
+
else:
|
|
479
|
+
try:
|
|
480
|
+
# Off the event loop, like the agreement export. An invalid
|
|
481
|
+
# workbook is a failed download: nothing of it is written.
|
|
482
|
+
rows = await asyncio.to_thread(parse_excel, content)
|
|
483
|
+
except ValueError as error:
|
|
484
|
+
failure = error
|
|
485
|
+
if failure is not None:
|
|
486
|
+
with self._session_factory() as session:
|
|
487
|
+
synced_as_of = session.scalar(
|
|
488
|
+
select(DepartmentSync.excel_stamp).where(
|
|
489
|
+
DepartmentSync.agreement_id == agreement_id,
|
|
490
|
+
DepartmentSync.department == department,
|
|
491
|
+
)
|
|
492
|
+
)
|
|
493
|
+
if synced_as_of is None:
|
|
494
|
+
raise ContractError(
|
|
495
|
+
ContractErrorCode.DEPARTMENT_UNAVAILABLE,
|
|
496
|
+
"scope.department",
|
|
497
|
+
f"Department {department} was never synced for {agreement_id} "
|
|
498
|
+
f"and its download failed: {failure}",
|
|
499
|
+
) from failure
|
|
500
|
+
_LOGGER.warning(
|
|
501
|
+
"department %s of %s: download failed, keeping the list as of %s: %s",
|
|
502
|
+
department,
|
|
503
|
+
agreement_id,
|
|
504
|
+
synced_as_of,
|
|
505
|
+
failure,
|
|
506
|
+
)
|
|
507
|
+
return False
|
|
508
|
+
|
|
509
|
+
return await _run_apply(
|
|
510
|
+
asyncio.to_thread(
|
|
511
|
+
self._apply_department, agreement_id, department, stamp, rows, request_id
|
|
512
|
+
)
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
def _parse_and_apply(
|
|
516
|
+
self,
|
|
517
|
+
agreement_id: str,
|
|
518
|
+
stamp: datetime,
|
|
519
|
+
content: bytes,
|
|
520
|
+
expected_count: int | None,
|
|
521
|
+
request_id: str,
|
|
522
|
+
) -> bool:
|
|
523
|
+
rows = parse_excel(content)
|
|
524
|
+
if expected_count is not None and len({row.ficha_id for row in rows}) < expected_count:
|
|
525
|
+
# A well-formed workbook can still be missing rows. The agreement's
|
|
526
|
+
# ficha count from ``GET /`` matches the export for the same stamp
|
|
527
|
+
# (docs/endpoints.md), so a shorter export is incomplete: write
|
|
528
|
+
# nothing, so the checkpoint stays put and a retry is possible.
|
|
529
|
+
raise ValueError(
|
|
530
|
+
f"Incomplete Excel export for {agreement_id}: "
|
|
531
|
+
f"{len(rows)} rows, expected {expected_count}"
|
|
532
|
+
)
|
|
533
|
+
return self._apply(agreement_id, stamp, rows, request_id)
|
|
534
|
+
|
|
535
|
+
def _apply(
|
|
536
|
+
self,
|
|
537
|
+
agreement_id: str,
|
|
538
|
+
stamp: datetime,
|
|
539
|
+
rows: Sequence[ExcelFicha],
|
|
540
|
+
request_id: str,
|
|
541
|
+
) -> bool:
|
|
542
|
+
synced_at = self._now()
|
|
543
|
+
uploaded = self._upload_inputs(stamp, rows)
|
|
544
|
+
# One transaction for the reads and the writes: the derived columns
|
|
545
|
+
# (pending flags, input_hash and its provenance) are written from ficha,
|
|
546
|
+
# ficha_card and pdf state read in the same transaction. The checkpoint
|
|
547
|
+
# update comes first, so on SQLite the write lock is held from before
|
|
548
|
+
# the reads; card and PDF writers wait for this commit instead of
|
|
549
|
+
# landing between the read and the write. Issue #153 tracks better
|
|
550
|
+
# approaches once the pilot has real usage logs.
|
|
551
|
+
with self._session_factory.begin() as session:
|
|
552
|
+
upsert(
|
|
553
|
+
session,
|
|
554
|
+
Agreement,
|
|
555
|
+
[
|
|
556
|
+
{
|
|
557
|
+
"agreement_id": agreement_id,
|
|
558
|
+
"excel_stamp": stamp,
|
|
559
|
+
"excel_synced_at": synced_at,
|
|
560
|
+
"excel_request_id": request_id,
|
|
561
|
+
"excel_ficha_count": len(rows),
|
|
562
|
+
}
|
|
563
|
+
],
|
|
564
|
+
guard_column="excel_stamp",
|
|
565
|
+
)
|
|
566
|
+
checkpoint = session.execute(
|
|
567
|
+
select(Agreement.excel_stamp, Agreement.excel_request_id).where(
|
|
568
|
+
Agreement.agreement_id == agreement_id
|
|
569
|
+
)
|
|
570
|
+
).one()
|
|
571
|
+
if checkpoint.excel_stamp != stamp or checkpoint.excel_request_id != request_id:
|
|
572
|
+
return False
|
|
573
|
+
|
|
574
|
+
excel_rows = self._excel_ficha_rows(
|
|
575
|
+
session, agreement_id, stamp, rows, request_id, synced_at, uploaded
|
|
576
|
+
)
|
|
577
|
+
for new_row in excel_rows.new:
|
|
578
|
+
new_row["excel_stamp"] = stamp
|
|
579
|
+
membership_rows = [
|
|
580
|
+
{"ficha_id": row.ficha_id, "excel_stamp": stamp, "last_seen_at": synced_at}
|
|
581
|
+
for row in rows
|
|
582
|
+
]
|
|
583
|
+
upsert(session, Payload, excel_rows.payloads.values())
|
|
584
|
+
# New and existing fichas carry different columns; one call each keeps
|
|
585
|
+
# every upsert a single batch instead of one per column-set change.
|
|
586
|
+
upsert(session, Ficha, excel_rows.new, guard_column="row_stamp")
|
|
587
|
+
upsert(session, Ficha, excel_rows.existing, guard_column="row_stamp")
|
|
588
|
+
upsert(session, Ficha, membership_rows, guard_column="excel_stamp")
|
|
589
|
+
return True
|
|
590
|
+
|
|
591
|
+
def _apply_department(
|
|
592
|
+
self,
|
|
593
|
+
agreement_id: str,
|
|
594
|
+
department: str,
|
|
595
|
+
stamp: datetime,
|
|
596
|
+
rows: Sequence[ExcelFicha],
|
|
597
|
+
request_id: str,
|
|
598
|
+
) -> bool:
|
|
599
|
+
"""Apply one complete department list: every availability transition.
|
|
600
|
+
|
|
601
|
+
unknown -> yes/no and no -> yes create or move a ``ficha_department``
|
|
602
|
+
row to ``stamp``; yes -> yes moves it; yes -> no writes nothing for the
|
|
603
|
+
ficha, whose row keeps its older stamp. Agreement-wide membership
|
|
604
|
+
(``ficha.excel_stamp``) is never written here.
|
|
605
|
+
"""
|
|
606
|
+
synced_at = self._now()
|
|
607
|
+
uploaded = self._upload_inputs(stamp, rows)
|
|
608
|
+
# One transaction, checkpoint first, as in ``_apply``: a reader never
|
|
609
|
+
# sees the new checkpoint with the old rows, and an older export
|
|
610
|
+
# finishing late is rejected by the newer-stamp guard.
|
|
611
|
+
with self._session_factory.begin() as session:
|
|
612
|
+
upsert(
|
|
613
|
+
session,
|
|
614
|
+
DepartmentSync,
|
|
615
|
+
[
|
|
616
|
+
{
|
|
617
|
+
"agreement_id": agreement_id,
|
|
618
|
+
"department": department,
|
|
619
|
+
"excel_stamp": stamp,
|
|
620
|
+
"excel_synced_at": synced_at,
|
|
621
|
+
"excel_request_id": request_id,
|
|
622
|
+
"excel_ficha_count": len(rows),
|
|
623
|
+
}
|
|
624
|
+
],
|
|
625
|
+
guard_column="excel_stamp",
|
|
626
|
+
)
|
|
627
|
+
checkpoint = session.execute(
|
|
628
|
+
select(DepartmentSync.excel_stamp, DepartmentSync.excel_request_id).where(
|
|
629
|
+
DepartmentSync.agreement_id == agreement_id,
|
|
630
|
+
DepartmentSync.department == department,
|
|
631
|
+
)
|
|
632
|
+
).one()
|
|
633
|
+
if checkpoint.excel_stamp != stamp or checkpoint.excel_request_id != request_id:
|
|
634
|
+
return False
|
|
635
|
+
|
|
636
|
+
excel_rows = self._excel_ficha_rows(
|
|
637
|
+
session, agreement_id, stamp, rows, request_id, synced_at, uploaded
|
|
638
|
+
)
|
|
639
|
+
# Seen in this export, but excel_stamp (agreement-wide membership)
|
|
640
|
+
# is left out: only a full agreement export sets it.
|
|
641
|
+
for existing_row in excel_rows.existing:
|
|
642
|
+
existing_row["last_seen_at"] = synced_at
|
|
643
|
+
department_rows = [
|
|
644
|
+
{
|
|
645
|
+
"ficha_id": row.ficha_id,
|
|
646
|
+
"department": department,
|
|
647
|
+
"stamp": stamp,
|
|
648
|
+
"request_id": request_id,
|
|
649
|
+
}
|
|
650
|
+
for row in rows
|
|
651
|
+
]
|
|
652
|
+
upsert(session, Payload, excel_rows.payloads.values())
|
|
653
|
+
upsert(session, Ficha, excel_rows.new, guard_column="row_stamp")
|
|
654
|
+
upsert(session, Ficha, excel_rows.existing, guard_column="row_stamp")
|
|
655
|
+
upsert(session, FichaDepartment, department_rows, guard_column="stamp")
|
|
656
|
+
return True
|
|
657
|
+
|
|
658
|
+
def _upload_inputs(self, stamp: datetime, rows: Sequence[ExcelFicha]) -> dict[str, _BuiltInput]:
|
|
659
|
+
"""Build and store the inputs the apply will write, before its transaction.
|
|
660
|
+
|
|
661
|
+
A read-only pass over the state the apply transaction reads again: it
|
|
662
|
+
builds the canonical input of every ficha the transaction would
|
|
663
|
+
rebuild and stores the new ones with one ``put_many``, so the payload
|
|
664
|
+
I/O (one round trip per digest prefix, not per ficha) runs before the
|
|
665
|
+
write transaction opens. The store is content-addressed: an input
|
|
666
|
+
whose transaction later aborts, or whose state moves before it, is
|
|
667
|
+
only an unreferenced, reusable payload. Returns each built input by
|
|
668
|
+
ficha ID, with what it was built from.
|
|
669
|
+
"""
|
|
670
|
+
with self._session_factory() as session:
|
|
671
|
+
state = _InputState.read(session, rows)
|
|
672
|
+
built: dict[str, _BuiltInput] = {}
|
|
673
|
+
|
|
674
|
+
def new_inputs() -> Iterator[tuple[str, bytes]]:
|
|
675
|
+
for row in rows:
|
|
676
|
+
if not state.writes(row, stamp) or state.reusable_input(row) is not None:
|
|
677
|
+
continue
|
|
678
|
+
source = state.input_source(row)
|
|
679
|
+
canonical_input = self._canonical_input(source)
|
|
680
|
+
built_input = _BuiltInput.of(source, canonical_input)
|
|
681
|
+
built[row.ficha_id] = built_input
|
|
682
|
+
if built_input.input_hash != source.current_hash:
|
|
683
|
+
yield built_input.input_hash, canonical_input
|
|
684
|
+
|
|
685
|
+
self._put_inputs(new_inputs())
|
|
686
|
+
return built
|
|
687
|
+
|
|
688
|
+
def _put_inputs(self, inputs: Iterable[tuple[str, bytes]]) -> None:
|
|
689
|
+
"""Store canonical inputs in one batch and check the digests the store returns."""
|
|
690
|
+
expected: list[str] = []
|
|
691
|
+
|
|
692
|
+
def bodies() -> Iterator[bytes]:
|
|
693
|
+
for input_hash, canonical_input in inputs:
|
|
694
|
+
expected.append(input_hash)
|
|
695
|
+
yield canonical_input
|
|
696
|
+
|
|
697
|
+
if self._payload_store.put_many(bodies(), "application/json") != expected:
|
|
698
|
+
raise RuntimeError("payload store returned an unexpected digest")
|
|
699
|
+
|
|
700
|
+
def _excel_ficha_rows(
|
|
701
|
+
self,
|
|
702
|
+
session: Session,
|
|
703
|
+
agreement_id: str,
|
|
704
|
+
stamp: datetime,
|
|
705
|
+
rows: Sequence[ExcelFicha],
|
|
706
|
+
request_id: str,
|
|
707
|
+
synced_at: datetime,
|
|
708
|
+
uploaded: Mapping[str, _BuiltInput],
|
|
709
|
+
) -> _ExcelFichaRows:
|
|
710
|
+
"""Build the Excel-field upserts of the rows newer than each ficha's row_stamp.
|
|
711
|
+
|
|
712
|
+
Each written row carries its refreshed ``input_hash`` and provenance,
|
|
713
|
+
built from the latest card and stored PDF text read in ``session``.
|
|
714
|
+
New fichas also carry ``first_seen_at`` and ``last_seen_at``.
|
|
715
|
+
|
|
716
|
+
An input in ``uploaded`` (stored by :meth:`_upload_inputs`) is reused
|
|
717
|
+
when it was built from the same Excel row, card features and PDF text
|
|
718
|
+
read here; any other input is built and stored here, in one batch.
|
|
719
|
+
"""
|
|
720
|
+
state = _InputState.read(session, rows)
|
|
721
|
+
late_inputs: list[tuple[str, bytes]] = []
|
|
722
|
+
|
|
723
|
+
result = _ExcelFichaRows()
|
|
724
|
+
for row in rows:
|
|
725
|
+
existing = state.existing.get(row.ficha_id)
|
|
726
|
+
card_stamp = state.card_stamp(row)
|
|
727
|
+
text_sha256 = state.text_sha256(row)
|
|
728
|
+
if not state.writes(row, stamp):
|
|
729
|
+
continue
|
|
730
|
+
|
|
731
|
+
# Same Excel row, built from the same card and PDF text: the input
|
|
732
|
+
# is unchanged (the usual case on a new site stamp), so neither the
|
|
733
|
+
# PDF text nor the input is read or stored again.
|
|
734
|
+
reused_hash = state.reusable_input(row)
|
|
735
|
+
if reused_hash is not None:
|
|
736
|
+
input_hash = reused_hash
|
|
737
|
+
else:
|
|
738
|
+
source = state.input_source(row)
|
|
739
|
+
built_input = uploaded.get(row.ficha_id)
|
|
740
|
+
if built_input is None or not built_input.built_from(source):
|
|
741
|
+
# The state moved since the pre-transaction pass (or the
|
|
742
|
+
# ficha was not in it): build the input from what is read here.
|
|
743
|
+
canonical_input = self._canonical_input(source)
|
|
744
|
+
built_input = _BuiltInput.of(source, canonical_input)
|
|
745
|
+
if built_input.input_hash != source.current_hash:
|
|
746
|
+
late_inputs.append((built_input.input_hash, canonical_input))
|
|
747
|
+
input_hash = built_input.input_hash
|
|
748
|
+
# Payloads are content-addressed by SHA-256: an input equal to
|
|
749
|
+
# the current one is already stored and has its payload row.
|
|
750
|
+
if input_hash != source.current_hash:
|
|
751
|
+
result.payloads[input_hash] = {
|
|
752
|
+
"payload_sha256": input_hash,
|
|
753
|
+
"content_type": "application/json",
|
|
754
|
+
"size_bytes": built_input.size_bytes,
|
|
755
|
+
"storage_uri": self._payload_store.storage_uri(input_hash),
|
|
756
|
+
"stored_at": synced_at,
|
|
757
|
+
}
|
|
758
|
+
ficha_row: dict[str, object] = {
|
|
759
|
+
"ficha_id": row.ficha_id,
|
|
760
|
+
"agreement_id": agreement_id,
|
|
761
|
+
"catalogue": row.catalogue,
|
|
762
|
+
"category": row.category,
|
|
763
|
+
"description": row.description,
|
|
764
|
+
"marca": row.marca,
|
|
765
|
+
"nro_parte": row.nro_parte,
|
|
766
|
+
"estado": row.estado,
|
|
767
|
+
"pdf_url": row.pdf_url,
|
|
768
|
+
"excel_hash": row.excel_hash,
|
|
769
|
+
# The request that supplied these Excel fields: written
|
|
770
|
+
# under the row-stamp guard, never by membership.
|
|
771
|
+
"excel_request_id": request_id,
|
|
772
|
+
"row_stamp": stamp,
|
|
773
|
+
"input_hash": input_hash,
|
|
774
|
+
"input_card_stamp": card_stamp,
|
|
775
|
+
"input_pdf_text_sha256": text_sha256,
|
|
776
|
+
"card_pending": card_stamp is None or card_stamp < stamp,
|
|
777
|
+
# Pending only while the PDF itself was never fetched: a
|
|
778
|
+
# stored PDF without extractable text is not retried.
|
|
779
|
+
"pdf_pending": row.pdf_url is not None and row.pdf_url not in state.pdf_text_hashes,
|
|
780
|
+
"extraction_pending": existing is None
|
|
781
|
+
or existing.extraction_pending
|
|
782
|
+
or existing.input_hash != input_hash,
|
|
783
|
+
}
|
|
784
|
+
if existing is None:
|
|
785
|
+
ficha_row.update({"first_seen_at": synced_at, "last_seen_at": synced_at})
|
|
786
|
+
result.new.append(ficha_row)
|
|
787
|
+
else:
|
|
788
|
+
result.existing.append(ficha_row)
|
|
789
|
+
if late_inputs:
|
|
790
|
+
self._put_inputs(late_inputs)
|
|
791
|
+
return result
|
|
792
|
+
|
|
793
|
+
def _canonical_input(self, source: _InputSource) -> bytes:
|
|
794
|
+
"""Build a ficha's canonical input, reading its PDF text from the store."""
|
|
795
|
+
pdf_text = (
|
|
796
|
+
self._payload_store.get(source.text_sha256) if source.text_sha256 is not None else None
|
|
797
|
+
)
|
|
798
|
+
return canonical_extraction_input(source.row, source.features, pdf_text)
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
class _ErrorPageError(ValueError):
|
|
802
|
+
"""The site answered a download with its HTTP 200 error page."""
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
async def _download(client: HttpClient, base_url: str, form: SearchForm) -> tuple[bytes, str]:
|
|
806
|
+
"""Download an export; raise on an HTTP error status or the site's error page."""
|
|
807
|
+
response = await post_download_response(client, base_url, form)
|
|
808
|
+
response.raise_for_status()
|
|
809
|
+
if response.extensions["is_error_page"]:
|
|
810
|
+
raise _ErrorPageError("download returned the site's error page")
|
|
811
|
+
request_id = response.extensions.get("request_id")
|
|
812
|
+
if not isinstance(request_id, str):
|
|
813
|
+
raise RuntimeError("download response has no logged request ID")
|
|
814
|
+
return response.content, request_id
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
async def _run_until_stopped(
|
|
818
|
+
work: Coroutine[Any, Any, tuple[str, ...]], stop: threading.Event
|
|
819
|
+
) -> tuple[str, ...]:
|
|
820
|
+
"""Await work in a worker thread; on cancellation, ask it to stop and wait for it.
|
|
821
|
+
|
|
822
|
+
A worker thread can't be cancelled: ``stop`` asks it to finish after the
|
|
823
|
+
item in progress, and the cancellation propagates once it has returned,
|
|
824
|
+
so nothing keeps writing after the caller was told the sync stopped.
|
|
825
|
+
"""
|
|
826
|
+
task = asyncio.ensure_future(work)
|
|
827
|
+
try:
|
|
828
|
+
return await asyncio.shield(task)
|
|
829
|
+
except asyncio.CancelledError:
|
|
830
|
+
stop.set()
|
|
831
|
+
while not task.done():
|
|
832
|
+
try:
|
|
833
|
+
await asyncio.shield(task)
|
|
834
|
+
except asyncio.CancelledError:
|
|
835
|
+
continue
|
|
836
|
+
except Exception:
|
|
837
|
+
break
|
|
838
|
+
if not task.cancelled():
|
|
839
|
+
task.exception() # mark a failure as retrieved
|
|
840
|
+
raise
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
async def _run_apply(work: Coroutine[Any, Any, bool]) -> bool:
|
|
844
|
+
"""Await an apply running in a worker thread, outliving a cancellation."""
|
|
845
|
+
apply = asyncio.ensure_future(work)
|
|
846
|
+
try:
|
|
847
|
+
return await asyncio.shield(apply)
|
|
848
|
+
except asyncio.CancelledError:
|
|
849
|
+
# The worker thread can't be stopped: keep holding the caller's sync
|
|
850
|
+
# lock until it has finished, so a retry sees its checkpoint instead
|
|
851
|
+
# of downloading the export again. Then propagate the cancellation.
|
|
852
|
+
while not apply.done():
|
|
853
|
+
try:
|
|
854
|
+
await asyncio.shield(apply)
|
|
855
|
+
except asyncio.CancelledError:
|
|
856
|
+
continue
|
|
857
|
+
except Exception:
|
|
858
|
+
break
|
|
859
|
+
if not apply.cancelled():
|
|
860
|
+
apply.exception() # mark a failure as retrieved
|
|
861
|
+
raise
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
@dataclass
|
|
865
|
+
class _ExcelFichaRows:
|
|
866
|
+
"""Excel-field ficha upserts and the input payloads they reference."""
|
|
867
|
+
|
|
868
|
+
payloads: dict[str, dict[str, object]] = field(default_factory=dict)
|
|
869
|
+
new: list[dict[str, object]] = field(default_factory=list)
|
|
870
|
+
existing: list[dict[str, object]] = field(default_factory=list)
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
@dataclass(frozen=True)
|
|
874
|
+
class _ExistingFicha:
|
|
875
|
+
row_stamp: datetime
|
|
876
|
+
excel_hash: str
|
|
877
|
+
input_hash: str | None
|
|
878
|
+
input_card_stamp: datetime | None
|
|
879
|
+
input_pdf_text_sha256: str | None
|
|
880
|
+
extraction_pending: bool
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def _existing_fichas(session: Session, ficha_ids: Sequence[str]) -> dict[str, _ExistingFicha]:
|
|
884
|
+
existing: dict[str, _ExistingFicha] = {}
|
|
885
|
+
for chunk in chunks(ficha_ids):
|
|
886
|
+
for ficha in session.execute(
|
|
887
|
+
select(
|
|
888
|
+
Ficha.ficha_id,
|
|
889
|
+
Ficha.row_stamp,
|
|
890
|
+
Ficha.excel_hash,
|
|
891
|
+
Ficha.input_hash,
|
|
892
|
+
Ficha.input_card_stamp,
|
|
893
|
+
Ficha.input_pdf_text_sha256,
|
|
894
|
+
Ficha.extraction_pending,
|
|
895
|
+
).where(Ficha.ficha_id.in_(chunk))
|
|
896
|
+
):
|
|
897
|
+
existing[ficha.ficha_id] = _ExistingFicha(
|
|
898
|
+
row_stamp=ficha.row_stamp,
|
|
899
|
+
excel_hash=ficha.excel_hash,
|
|
900
|
+
input_hash=ficha.input_hash,
|
|
901
|
+
input_card_stamp=ficha.input_card_stamp,
|
|
902
|
+
input_pdf_text_sha256=ficha.input_pdf_text_sha256,
|
|
903
|
+
extraction_pending=ficha.extraction_pending,
|
|
904
|
+
)
|
|
905
|
+
return existing
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _latest_cards(
|
|
909
|
+
session: Session, ficha_ids: Sequence[str]
|
|
910
|
+
) -> dict[str, tuple[datetime, list[Feature] | None]]:
|
|
911
|
+
latest: dict[str, tuple[datetime, list[Feature] | None]] = {}
|
|
912
|
+
for chunk in chunks(ficha_ids):
|
|
913
|
+
ranked_cards = (
|
|
914
|
+
select(
|
|
915
|
+
FichaCard.ficha_id.label("ficha_id"),
|
|
916
|
+
FichaCard.stamp.label("stamp"),
|
|
917
|
+
FichaCard.features.label("features"),
|
|
918
|
+
func.row_number()
|
|
919
|
+
.over(
|
|
920
|
+
partition_by=FichaCard.ficha_id,
|
|
921
|
+
order_by=(
|
|
922
|
+
FichaCard.stamp.desc(),
|
|
923
|
+
FichaCard.observed_at.desc(),
|
|
924
|
+
FichaCard.card_id.desc(),
|
|
925
|
+
),
|
|
926
|
+
)
|
|
927
|
+
.label("rank"),
|
|
928
|
+
)
|
|
929
|
+
.where(FichaCard.ficha_id.in_(chunk))
|
|
930
|
+
.subquery()
|
|
931
|
+
)
|
|
932
|
+
for card in session.execute(
|
|
933
|
+
select(
|
|
934
|
+
ranked_cards.c.ficha_id,
|
|
935
|
+
ranked_cards.c.stamp,
|
|
936
|
+
ranked_cards.c.features,
|
|
937
|
+
).where(ranked_cards.c.rank == 1)
|
|
938
|
+
).mappings():
|
|
939
|
+
latest[card["ficha_id"]] = (card["stamp"], card["features"])
|
|
940
|
+
return latest
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _pdf_text_hashes(session: Session, pdf_urls: Sequence[str]) -> dict[str, str | None]:
|
|
944
|
+
hashes: dict[str, str | None] = {}
|
|
945
|
+
for chunk in chunks(pdf_urls):
|
|
946
|
+
for pdf in session.execute(
|
|
947
|
+
select(Pdf.pdf_url, Pdf.text_sha256).where(Pdf.pdf_url.in_(chunk))
|
|
948
|
+
).mappings():
|
|
949
|
+
hashes[pdf["pdf_url"]] = pdf["text_sha256"]
|
|
950
|
+
return hashes
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
@dataclass(frozen=True, slots=True)
|
|
954
|
+
class _InputSource:
|
|
955
|
+
"""A ficha whose canonical input must be built, and what it is built from."""
|
|
956
|
+
|
|
957
|
+
row: ExcelFicha
|
|
958
|
+
features: list[Feature] | None
|
|
959
|
+
text_sha256: str | None
|
|
960
|
+
current_hash: str | None
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
@dataclass(frozen=True, slots=True)
|
|
964
|
+
class _BuiltInput:
|
|
965
|
+
"""A built canonical input, with the sources it was built from."""
|
|
966
|
+
|
|
967
|
+
row: ExcelFicha
|
|
968
|
+
features: list[Feature] | None
|
|
969
|
+
text_sha256: str | None
|
|
970
|
+
input_hash: str
|
|
971
|
+
size_bytes: int
|
|
972
|
+
|
|
973
|
+
@classmethod
|
|
974
|
+
def of(cls, source: _InputSource, canonical_input: bytes) -> _BuiltInput:
|
|
975
|
+
return cls(
|
|
976
|
+
row=source.row,
|
|
977
|
+
features=source.features,
|
|
978
|
+
text_sha256=source.text_sha256,
|
|
979
|
+
input_hash=hashlib.sha256(canonical_input).hexdigest(),
|
|
980
|
+
size_bytes=len(canonical_input),
|
|
981
|
+
)
|
|
982
|
+
|
|
983
|
+
def built_from(self, source: _InputSource) -> bool:
|
|
984
|
+
"""Whether this input's bytes are the ones ``source`` would build."""
|
|
985
|
+
return (self.row, self.features, self.text_sha256) == (
|
|
986
|
+
source.row,
|
|
987
|
+
source.features,
|
|
988
|
+
source.text_sha256,
|
|
989
|
+
)
|
|
990
|
+
|
|
991
|
+
|
|
992
|
+
@dataclass(frozen=True, slots=True)
|
|
993
|
+
class _InputState:
|
|
994
|
+
"""The ficha, card and PDF state a ficha's canonical input is derived from."""
|
|
995
|
+
|
|
996
|
+
existing: dict[str, _ExistingFicha]
|
|
997
|
+
latest_cards: dict[str, tuple[datetime, list[Feature] | None]]
|
|
998
|
+
pdf_text_hashes: dict[str, str | None]
|
|
999
|
+
|
|
1000
|
+
@classmethod
|
|
1001
|
+
def read(cls, session: Session, rows: Sequence[ExcelFicha]) -> _InputState:
|
|
1002
|
+
ficha_ids = sorted({row.ficha_id for row in rows})
|
|
1003
|
+
pdf_urls = sorted({row.pdf_url for row in rows if row.pdf_url is not None})
|
|
1004
|
+
return cls(
|
|
1005
|
+
existing=_existing_fichas(session, ficha_ids),
|
|
1006
|
+
latest_cards=_latest_cards(session, ficha_ids),
|
|
1007
|
+
pdf_text_hashes=_pdf_text_hashes(session, pdf_urls),
|
|
1008
|
+
)
|
|
1009
|
+
|
|
1010
|
+
def writes(self, row: ExcelFicha, stamp: datetime) -> bool:
|
|
1011
|
+
"""Whether an export at ``stamp`` writes the row (it is newer than the ficha's)."""
|
|
1012
|
+
existing = self.existing.get(row.ficha_id)
|
|
1013
|
+
return existing is None or existing.row_stamp < stamp
|
|
1014
|
+
|
|
1015
|
+
def reusable_input(self, row: ExcelFicha) -> str | None:
|
|
1016
|
+
"""The ficha's stored input if it was built from this Excel row, card and PDF text."""
|
|
1017
|
+
existing = self.existing.get(row.ficha_id)
|
|
1018
|
+
if (
|
|
1019
|
+
existing is not None
|
|
1020
|
+
and existing.excel_hash == row.excel_hash
|
|
1021
|
+
and existing.input_card_stamp == self.card_stamp(row)
|
|
1022
|
+
and existing.input_pdf_text_sha256 == self.text_sha256(row)
|
|
1023
|
+
):
|
|
1024
|
+
return existing.input_hash
|
|
1025
|
+
return None
|
|
1026
|
+
|
|
1027
|
+
def input_source(self, row: ExcelFicha) -> _InputSource:
|
|
1028
|
+
"""What to build the row's input from: its latest card and stored PDF text."""
|
|
1029
|
+
existing = self.existing.get(row.ficha_id)
|
|
1030
|
+
latest_card = self.latest_cards.get(row.ficha_id)
|
|
1031
|
+
return _InputSource(
|
|
1032
|
+
row=row,
|
|
1033
|
+
features=latest_card[1] if latest_card is not None else None,
|
|
1034
|
+
text_sha256=self.text_sha256(row),
|
|
1035
|
+
current_hash=existing.input_hash if existing is not None else None,
|
|
1036
|
+
)
|
|
1037
|
+
|
|
1038
|
+
def card_stamp(self, row: ExcelFicha) -> datetime | None:
|
|
1039
|
+
"""The stamp of the ficha's latest card, if any."""
|
|
1040
|
+
latest_card = self.latest_cards.get(row.ficha_id)
|
|
1041
|
+
return latest_card[0] if latest_card is not None else None
|
|
1042
|
+
|
|
1043
|
+
def text_sha256(self, row: ExcelFicha) -> str | None:
|
|
1044
|
+
"""The digest of the stored text of the row's PDF, if any."""
|
|
1045
|
+
return self.pdf_text_hashes.get(row.pdf_url) if row.pdf_url is not None else None
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
def query_needs(session: Session, contract: ValidatedContract) -> frozenset[str]:
|
|
1049
|
+
"""The attributes the query's predicates and facets use (``needs``).
|
|
1050
|
+
|
|
1051
|
+
Every predicate's attribute (already canonical) except text predicates,
|
|
1052
|
+
which match the description. Requested facets other than the structural
|
|
1053
|
+
fields, each resolved through its ``merged_into`` chain to the accepted
|
|
1054
|
+
attribute it ends at, as the facet query resolves them; with
|
|
1055
|
+
``facets: "all"``, every accepted attribute ``attribute_scope`` records
|
|
1056
|
+
for a category of the scope's current members. Structural fields come
|
|
1057
|
+
from the Excel and are never needs.
|
|
1058
|
+
"""
|
|
1059
|
+
needs = {predicate.attribute for predicate in contract.predicates if predicate.op != "text"}
|
|
1060
|
+
facets = (contract.include or {}).get("facets")
|
|
1061
|
+
if facets is None:
|
|
1062
|
+
return frozenset(needs)
|
|
1063
|
+
attributes = {
|
|
1064
|
+
attribute.attribute_id: attribute for attribute in session.scalars(select(Attribute))
|
|
1065
|
+
}
|
|
1066
|
+
if facets == "all":
|
|
1067
|
+
categories = select(Ficha.category).where(*membership_conditions(contract.scope))
|
|
1068
|
+
names: Collection[str] = session.scalars(
|
|
1069
|
+
select(AttributeScope.attribute_id)
|
|
1070
|
+
.where(AttributeScope.category.in_(categories))
|
|
1071
|
+
.distinct()
|
|
1072
|
+
).all()
|
|
1073
|
+
else:
|
|
1074
|
+
names = [name for name in cast(list[str], facets) if name not in STRUCTURAL_FIELDS]
|
|
1075
|
+
for name in names:
|
|
1076
|
+
root = _accepted_root(name, attributes)
|
|
1077
|
+
if root is not None:
|
|
1078
|
+
needs.add(root)
|
|
1079
|
+
return frozenset(needs)
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
def _accepted_root(attribute_id: str, attributes: Mapping[str, Attribute]) -> str | None:
|
|
1083
|
+
"""The accepted attribute a ``merged_into`` chain ends at, if any."""
|
|
1084
|
+
seen: set[str] = set()
|
|
1085
|
+
attribute = attributes.get(attribute_id)
|
|
1086
|
+
while attribute is not None and attribute.merged_into is not None:
|
|
1087
|
+
if attribute.attribute_id in seen:
|
|
1088
|
+
return None
|
|
1089
|
+
seen.add(attribute.attribute_id)
|
|
1090
|
+
attribute = attributes.get(attribute.merged_into)
|
|
1091
|
+
if attribute is None or attribute.status != "accepted":
|
|
1092
|
+
return None
|
|
1093
|
+
return attribute.attribute_id
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
def _list_current(session: Session, scope: Mapping[str, str], stamp: datetime) -> bool:
|
|
1097
|
+
"""Whether the scope's list is current under ``stamp``: the Excel step would skip.
|
|
1098
|
+
|
|
1099
|
+
The ``department_sync`` checkpoint when the scope has a department (a
|
|
1100
|
+
never-synced department has no row and is never current), else the
|
|
1101
|
+
agreement's ``excel_stamp`` (NULL: never synced). A scope without an
|
|
1102
|
+
agreement is never current.
|
|
1103
|
+
"""
|
|
1104
|
+
agreement_id = scope.get("agreement")
|
|
1105
|
+
if agreement_id is None:
|
|
1106
|
+
# ``sync`` refuses such a scope; never report it current.
|
|
1107
|
+
return False
|
|
1108
|
+
department = scope.get("department")
|
|
1109
|
+
if department is not None:
|
|
1110
|
+
checkpoint = session.get(DepartmentSync, (agreement_id, department))
|
|
1111
|
+
return checkpoint is not None and checkpoint.excel_stamp >= stamp
|
|
1112
|
+
agreement = session.get(Agreement, agreement_id)
|
|
1113
|
+
return (
|
|
1114
|
+
agreement is not None
|
|
1115
|
+
and agreement.excel_stamp is not None
|
|
1116
|
+
and agreement.excel_stamp >= stamp
|
|
1117
|
+
)
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
def _member_work_pending(session: Session, scope: Mapping[str, str], stamp: datetime) -> bool:
|
|
1121
|
+
"""Whether a member ficha still needs its card or its rules pass under ``stamp``.
|
|
1122
|
+
|
|
1123
|
+
A card the site does not return under the stamp (not on any page, and its
|
|
1124
|
+
part-number lookup already answered or impossible) is settled for the
|
|
1125
|
+
stamp (``card_settled``), so it does not keep the shortcut off.
|
|
1126
|
+
"""
|
|
1127
|
+
return bool(
|
|
1128
|
+
session.scalar(
|
|
1129
|
+
select(
|
|
1130
|
+
exists().where(
|
|
1131
|
+
*membership_conditions(scope),
|
|
1132
|
+
or_(~card_settled(stamp), _awaits_rules_pass()),
|
|
1133
|
+
)
|
|
1134
|
+
)
|
|
1135
|
+
)
|
|
1136
|
+
)
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def _rules_pass_due(now: datetime) -> Any:
|
|
1140
|
+
"""No failed rules pass recorded for the ficha's current input, or its backoff has passed."""
|
|
1141
|
+
return or_(
|
|
1142
|
+
Ficha.rules_failures == 0,
|
|
1143
|
+
Ficha.rules_failed_input_hash.is_(None),
|
|
1144
|
+
Ficha.rules_failed_input_hash != Ficha.input_hash,
|
|
1145
|
+
Ficha.rules_retry_at.is_(None),
|
|
1146
|
+
Ficha.rules_retry_at <= now,
|
|
1147
|
+
)
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
def _awaits_rules_pass() -> Any:
|
|
1151
|
+
"""The ficha has an input and no ``ok`` rules pass for it (``v_current_extraction``)."""
|
|
1152
|
+
return Ficha.input_hash.is_not(None) & ~exists().where(
|
|
1153
|
+
Extraction.ficha_id == Ficha.ficha_id,
|
|
1154
|
+
Extraction.input_hash == Ficha.input_hash,
|
|
1155
|
+
Extraction.model == "rules",
|
|
1156
|
+
Extraction.status == "ok",
|
|
1157
|
+
)
|