perucompras-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. perucompras_cli-0.1.0.dist-info/METADATA +429 -0
  2. perucompras_cli-0.1.0.dist-info/RECORD +50 -0
  3. perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
  4. perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
  6. piloto_ai_cli/__init__.py +51 -0
  7. piloto_ai_cli/__main__.py +5 -0
  8. piloto_ai_cli/api.py +394 -0
  9. piloto_ai_cli/attribute_text.py +106 -0
  10. piloto_ai_cli/attributes_service.py +250 -0
  11. piloto_ai_cli/auto_tag.py +65 -0
  12. piloto_ai_cli/backoff.py +25 -0
  13. piloto_ai_cli/cards.py +871 -0
  14. piloto_ai_cli/cli.py +602 -0
  15. piloto_ai_cli/connectors.py +106 -0
  16. piloto_ai_cli/database.py +491 -0
  17. piloto_ai_cli/enrichment.py +557 -0
  18. piloto_ai_cli/errors.py +92 -0
  19. piloto_ai_cli/excel.py +186 -0
  20. piloto_ai_cli/extraction.py +1316 -0
  21. piloto_ai_cli/health.py +398 -0
  22. piloto_ai_cli/health_workflow.py +1060 -0
  23. piloto_ai_cli/http_client.py +610 -0
  24. piloto_ai_cli/llm_client.py +259 -0
  25. piloto_ai_cli/llm_extraction.py +444 -0
  26. piloto_ai_cli/llm_output.py +90 -0
  27. piloto_ai_cli/pane.py +303 -0
  28. piloto_ai_cli/parsers.py +477 -0
  29. piloto_ai_cli/payload_store.py +227 -0
  30. piloto_ai_cli/pdf_parser.py +12 -0
  31. piloto_ai_cli/py.typed +0 -0
  32. piloto_ai_cli/query_compiler.py +1112 -0
  33. piloto_ai_cli/query_result.py +175 -0
  34. piloto_ai_cli/query_service.py +199 -0
  35. piloto_ai_cli/reextract.py +129 -0
  36. piloto_ai_cli/review.py +217 -0
  37. piloto_ai_cli/rules.py +67 -0
  38. piloto_ai_cli/run_log.py +230 -0
  39. piloto_ai_cli/schema/__init__.py +25 -0
  40. piloto_ai_cli/schema/contract-v1.schema.json +261 -0
  41. piloto_ai_cli/schema/contract.py +257 -0
  42. piloto_ai_cli/schema/migration_filters.py +59 -0
  43. piloto_ai_cli/schema/models.py +747 -0
  44. piloto_ai_cli/schema/snowflake_autogen.py +134 -0
  45. piloto_ai_cli/search_form.py +82 -0
  46. piloto_ai_cli/settings.py +174 -0
  47. piloto_ai_cli/snowflake_url.py +90 -0
  48. piloto_ai_cli/stamp_service.py +53 -0
  49. piloto_ai_cli/sync.py +1157 -0
  50. piloto_ai_cli/unit_converter.py +81 -0
@@ -0,0 +1,106 @@
1
+ """HTTP connectors for Perú Compras endpoints and external catalog sources."""
2
+
3
+ import asyncio
4
+ import threading
5
+
6
+ import httpx2
7
+
8
+ from piloto_ai_cli.errors import ParseError
9
+ from piloto_ai_cli.http_client import HttpClient
10
+ from piloto_ai_cli.search_form import SearchForm
11
+
12
+ HOME_URL = "https://buscadorcatalogos.perucompras.gob.pe/"
13
+ _SEARCH_URL = "https://buscadorcatalogos.perucompras.gob.pe/Search/Search"
14
+
15
+
16
+ async def post_search_response(client: HttpClient, form: SearchForm) -> httpx2.Response:
17
+ """Submit a search form and return its logged response."""
18
+ token = client.token
19
+ if token is None:
20
+ raise ValueError("bootstrap must be called before post_search")
21
+
22
+ response = await client.write_request(
23
+ "POST",
24
+ _SEARCH_URL,
25
+ endpoint="post_search",
26
+ data=form.to_form(antiforgery_token=token),
27
+ )
28
+ response.raise_for_status()
29
+ if response.extensions["is_error_page"]:
30
+ raise ParseError("search returned the site's error page")
31
+ return response
32
+
33
+
34
+ async def post_search(client: HttpClient, form: SearchForm) -> str:
35
+ """Submit a search form and return its HTML fragment."""
36
+ return (await post_search_response(client, form)).text
37
+
38
+
39
+ async def get_home(client: HttpClient, *, allow_error_page: bool = False) -> httpx2.Response:
40
+ """Fetch and log the home page while bootstrapping the client's session."""
41
+ return await client.bootstrap_response(HOME_URL, allow_error_page=allow_error_page)
42
+
43
+
44
+ _DOWNLOAD_LOCKS_GUARD = threading.Lock()
45
+ _DOWNLOAD_LOCKS: dict[str, threading.Lock] = {}
46
+
47
+
48
+ def _download_lock(agreement_filter: str) -> threading.Lock:
49
+ with _DOWNLOAD_LOCKS_GUARD:
50
+ return _DOWNLOAD_LOCKS.setdefault(agreement_filter, threading.Lock())
51
+
52
+
53
+ def _agreement_filter(search_form: SearchForm) -> str:
54
+ value = search_form.scope.get("agreement")
55
+ values = (value,) if isinstance(value, str) else tuple(value or ())
56
+ if len(values) != 1 or not values[0].strip():
57
+ raise ValueError("post_download requires exactly one agreement in the search form")
58
+ return values[0].strip()
59
+
60
+
61
+ async def post_download(client: HttpClient, base_url: str, search_form: SearchForm) -> bytes:
62
+ """Download one agreement's Excel export through the logged HTTP client."""
63
+ response = await post_download_response(client, base_url, search_form)
64
+ response.raise_for_status()
65
+ if response.extensions["is_error_page"]:
66
+ raise ValueError("site returned its error page")
67
+ return response.content
68
+
69
+
70
+ async def post_download_response(
71
+ client: HttpClient, base_url: str, search_form: SearchForm
72
+ ) -> httpx2.Response:
73
+ """Download one agreement's Excel export and return its logged response."""
74
+ token = client.token
75
+ if not token:
76
+ raise ValueError("post_download requires a token from bootstrap")
77
+
78
+ agreement_filter = _agreement_filter(search_form)
79
+ form = search_form.to_form(antiforgery_token=token)
80
+ lock = _download_lock(agreement_filter)
81
+ while not lock.acquire(blocking=False):
82
+ await asyncio.sleep(0.01)
83
+ try:
84
+ return await client.write_request(
85
+ "POST",
86
+ f"{base_url.rstrip('/')}/Search/Download",
87
+ endpoint="post_download",
88
+ excel_download=True,
89
+ data=form,
90
+ )
91
+ finally:
92
+ lock.release()
93
+
94
+
95
+ async def get_pdf(client: HttpClient, pdf_url: str) -> bytes:
96
+ """Download a ficha PDF through the request-logging HTTP client."""
97
+ response = await get_pdf_response(client, pdf_url)
98
+ response.raise_for_status()
99
+ if response.extensions["is_error_page"]:
100
+ raise ValueError("site returned its error page")
101
+ return response.content
102
+
103
+
104
+ async def get_pdf_response(client: HttpClient, pdf_url: str) -> httpx2.Response:
105
+ """Fetch a ficha PDF and return its logged response."""
106
+ return await client.write_request("GET", pdf_url, endpoint="get_pdf")
@@ -0,0 +1,491 @@
1
+ """SQLAlchemy engine and session helpers."""
2
+
3
+ import atexit
4
+ import os
5
+ import tempfile
6
+ import threading
7
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+ from typing import Any, cast
11
+
12
+ from sqlalchemy import (
13
+ Engine,
14
+ Table,
15
+ and_,
16
+ bindparam,
17
+ create_engine,
18
+ or_,
19
+ select,
20
+ text,
21
+ tuple_,
22
+ update,
23
+ )
24
+ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
25
+ from sqlalchemy.engine import make_url
26
+ from sqlalchemy.engine.interfaces import Dialect
27
+ from sqlalchemy.orm import Session, sessionmaker
28
+ from sqlalchemy.schema import UniqueConstraint
29
+ from sqlalchemy.sql.elements import TextClause
30
+
31
+ from piloto_ai_cli.schema.models import SCHEMA, Base, ExtractionConfig
32
+ from piloto_ai_cli.settings import MAX_PAGES_IN_FLIGHT, Settings
33
+
34
+ _SNOWFLAKE_UPSERT_CHUNK_SIZE = 1_000
35
+ # Bound list size for ``IN (...)`` filters on ids: Snowflake caps an IN list
36
+ # at 16,384 expressions and very large bound lists compile slowly.
37
+ QUERY_CHUNK_SIZE = 500
38
+
39
+
40
+ def chunks(values: Sequence[str]) -> Iterator[Sequence[str]]:
41
+ """``values`` in slices of at most ``QUERY_CHUNK_SIZE``, for bounded IN lists."""
42
+ for offset in range(0, len(values), QUERY_CHUNK_SIZE):
43
+ yield values[offset : offset + QUERY_CHUNK_SIZE]
44
+
45
+
46
+ def _natural_key(model: type[Base]) -> tuple[str, ...]:
47
+ table = cast(Table, model.__table__)
48
+ unique_constraints = sorted(
49
+ (
50
+ constraint
51
+ for constraint in table.constraints
52
+ if isinstance(constraint, UniqueConstraint)
53
+ ),
54
+ key=lambda constraint: (
55
+ constraint.name or "",
56
+ tuple(column.key for column in constraint.columns),
57
+ ),
58
+ )
59
+ if unique_constraints:
60
+ return tuple(column.key for column in unique_constraints[0].columns)
61
+ return tuple(column.key for column in table.primary_key.columns)
62
+
63
+
64
+ def _update_columns(
65
+ model: type[Base], key_columns: tuple[str, ...], row_columns: tuple[str, ...]
66
+ ) -> tuple[str, ...]:
67
+ """Supplied, model-approved columns a matched row may change.
68
+
69
+ A surrogate primary key keeps its first value, so rows that reference it
70
+ (for example lineage through ``extraction_id``) stay valid on replay.
71
+ """
72
+ table = cast(Table, model.__table__)
73
+ fixed = set(key_columns) | {column.key for column in table.primary_key.columns}
74
+ return tuple(
75
+ column for column in row_columns if column in model.__updatable__ and column not in fixed
76
+ )
77
+
78
+
79
+ def _required_columns(table: Table) -> frozenset[str]:
80
+ """Columns an INSERT must supply: NOT NULL, with no default of any kind."""
81
+ return frozenset(
82
+ column.key
83
+ for column in table.columns
84
+ if not column.nullable
85
+ and column.default is None
86
+ and column.server_default is None
87
+ and column is not table.autoincrement_column
88
+ )
89
+
90
+
91
+ def _require_existing_keys(
92
+ session: Session,
93
+ table: Table,
94
+ key_columns: tuple[str, ...],
95
+ rows: list[dict[str, Any]],
96
+ ) -> None:
97
+ """Reject sparse rows whose natural key has no existing row to update."""
98
+ keys = {tuple(row[column] for column in key_columns) for row in rows}
99
+ key_expression = tuple_(*(table.c[column] for column in key_columns))
100
+ found: set[tuple[Any, ...]] = set()
101
+ ordered_keys = list(keys)
102
+ for offset in range(0, len(ordered_keys), _SNOWFLAKE_UPSERT_CHUNK_SIZE):
103
+ chunk = ordered_keys[offset : offset + _SNOWFLAKE_UPSERT_CHUNK_SIZE]
104
+ result = session.execute(
105
+ select(*(table.c[column] for column in key_columns)).where(key_expression.in_(chunk))
106
+ )
107
+ found.update(tuple(row) for row in result)
108
+ missing = keys - found
109
+ if missing:
110
+ raise ValueError(
111
+ f"Rows for {table.name} omit required columns and can only update existing "
112
+ f"rows, but these keys do not exist: {sorted(missing, key=repr)[:5]}"
113
+ )
114
+
115
+
116
+ def _stamp_wins(existing: Any, candidate: Any) -> bool:
117
+ """Whether a duplicate row's guard stamp replaces the one already kept."""
118
+ return existing is None or (candidate is not None and candidate > existing)
119
+
120
+
121
+ def _coalesce_rows(
122
+ rows: list[dict[str, Any]],
123
+ key_columns: tuple[str, ...],
124
+ update_columns: tuple[str, ...],
125
+ guard_column: str | None,
126
+ ) -> list[dict[str, Any]]:
127
+ """Keep the first row's immutable values and coalesce approved updates."""
128
+ coalesced: dict[tuple[Any, ...], dict[str, Any]] = {}
129
+ for row in rows:
130
+ key = tuple(row[column] for column in key_columns)
131
+ existing = coalesced.get(key)
132
+ if existing is None:
133
+ coalesced[key] = row
134
+ elif update_columns and (
135
+ guard_column is None or _stamp_wins(existing[guard_column], row[guard_column])
136
+ ):
137
+ coalesced[key] = {
138
+ **existing,
139
+ **{column: row[column] for column in update_columns},
140
+ }
141
+ return list(coalesced.values())
142
+
143
+
144
+ def _snowflake_merge_statement(
145
+ model: type[Base],
146
+ dialect: Dialect,
147
+ key_columns: tuple[str, ...],
148
+ row_columns: tuple[str, ...],
149
+ guard_column: str | None,
150
+ row_count: int = 1,
151
+ *,
152
+ insert_missing: bool = True,
153
+ insert_only: bool = False,
154
+ ) -> TextClause:
155
+ table = cast(Table, model.__table__)
156
+ preparer = dialect.identifier_preparer
157
+ target = ".".join(preparer.quote(part) for part in (table.schema or SCHEMA, table.name))
158
+ names = {column.key: preparer.quote(column.name) for column in table.columns}
159
+ bind_names = {
160
+ (row_index, column): f"value_{row_index}_{column_index}"
161
+ for row_index in range(row_count)
162
+ for column_index, column in enumerate(row_columns)
163
+ }
164
+ source_rows = " UNION ALL ".join(
165
+ "SELECT "
166
+ + ", ".join(
167
+ f":{bind_names[row_index, column]} AS {names[column]}" for column in row_columns
168
+ )
169
+ for row_index in range(row_count)
170
+ )
171
+ on_clause = " AND ".join(
172
+ f"target.{names[column]} = source.{names[column]}" for column in key_columns
173
+ )
174
+ update_columns = () if insert_only else _update_columns(model, key_columns, row_columns)
175
+ matched_clause = ""
176
+ if update_columns:
177
+ guard = ""
178
+ if guard_column is not None:
179
+ guard = (
180
+ f" AND (target.{names[guard_column]} IS NULL OR "
181
+ f"target.{names[guard_column]} < source.{names[guard_column]})"
182
+ )
183
+ assignments = ", ".join(
184
+ f"{names[column]} = source.{names[column]}" for column in update_columns
185
+ )
186
+ matched_clause = f" WHEN MATCHED{guard} THEN UPDATE SET {assignments}"
187
+ not_matched_clause = ""
188
+ if insert_missing:
189
+ insert_columns = ", ".join(names[column] for column in row_columns)
190
+ source_values = ", ".join(f"source.{names[column]}" for column in row_columns)
191
+ not_matched_clause = (
192
+ f" WHEN NOT MATCHED THEN INSERT ({insert_columns}) VALUES ({source_values})"
193
+ )
194
+ statement = text(
195
+ f"MERGE INTO {target} AS target USING ({source_rows}) AS source "
196
+ f"ON {on_clause}{matched_clause}{not_matched_clause}"
197
+ )
198
+ return statement.bindparams(
199
+ *(
200
+ bindparam(bind_names[row_index, column], type_=table.c[column].type)
201
+ for row_index in range(row_count)
202
+ for column in row_columns
203
+ )
204
+ )
205
+
206
+
207
+ def upsert(
208
+ session: Session,
209
+ model: type[Base],
210
+ rows: Iterable[Mapping[str, Any]],
211
+ *,
212
+ guard_column: str | None = None,
213
+ insert_only: bool = False,
214
+ ) -> None:
215
+ """Insert rows by natural key, updating only each model's approved columns.
216
+
217
+ Append-only models do nothing on a key match. Rows that omit a required
218
+ column (NOT NULL without a default) are sparse updates: they only update
219
+ existing rows, and reject supplied non-updatable columns. ``guard_column``
220
+ limits approved updates to newer stamps. ``insert_only`` inserts missing
221
+ rows and leaves every existing row untouched, even its updatable columns,
222
+ so a row committed concurrently by another writer keeps its state; its rows
223
+ must be complete. Pending ORM changes are flushed
224
+ first, because these Core statements do not autoflush and the session is
225
+ expired afterwards.
226
+ """
227
+ table = cast(Table, model.__table__)
228
+ key_columns = _natural_key(model)
229
+ if not key_columns:
230
+ raise ValueError(f"{model.__name__} has no primary or unique key")
231
+ columns = {column.key: column for column in table.columns}
232
+ if guard_column is not None and guard_column not in columns:
233
+ raise ValueError(f"{guard_column!r} is not a column of {model.__name__}")
234
+ if insert_only and guard_column is not None:
235
+ raise ValueError("insert_only writes update nothing, so they take no guard_column")
236
+
237
+ batches: list[tuple[tuple[str, ...], list[dict[str, Any]]]] = []
238
+ batch_columns: tuple[str, ...] | None = None
239
+ batch: list[dict[str, Any]] = []
240
+ for row in rows:
241
+ unknown_columns = set(row) - columns.keys()
242
+ if unknown_columns:
243
+ raise ValueError(f"Unknown columns for {model.__name__}: {sorted(unknown_columns)}")
244
+ missing_keys = set(key_columns) - row.keys()
245
+ if missing_keys:
246
+ raise ValueError(f"Missing natural key columns: {sorted(missing_keys)}")
247
+ if guard_column is not None and guard_column not in row:
248
+ raise ValueError(f"Missing guard column {guard_column!r}")
249
+ row_columns = tuple(column for column in columns if column in row)
250
+ if row_columns != batch_columns:
251
+ if batch_columns is not None:
252
+ batches.append((batch_columns, batch))
253
+ batch_columns = row_columns
254
+ batch = []
255
+ batch.append(dict(row))
256
+
257
+ if batch_columns is not None:
258
+ batches.append((batch_columns, batch))
259
+ if not batches:
260
+ return
261
+
262
+ dialect = session.get_bind(mapper=model).dialect
263
+ if dialect.name not in {"sqlite", "snowflake"}:
264
+ raise NotImplementedError(f"Upserts are not supported for {dialect.name}")
265
+ session.flush()
266
+ required_columns = _required_columns(table)
267
+ primary_key_columns = tuple(
268
+ column.key for column in table.primary_key.columns if column.key not in key_columns
269
+ )
270
+ for row_columns, batch in batches:
271
+ insert_missing = required_columns <= set(row_columns)
272
+ if insert_only and not insert_missing:
273
+ missing_columns = sorted(required_columns - set(row_columns))
274
+ raise ValueError(
275
+ f"Insert-only rows for {model.__name__} miss required columns: {missing_columns}"
276
+ )
277
+ update_columns = () if insert_only else _update_columns(model, key_columns, row_columns)
278
+ if not insert_missing:
279
+ non_updatable_columns = (
280
+ set(row_columns) - set(key_columns) - set(primary_key_columns) - set(update_columns)
281
+ )
282
+ if non_updatable_columns:
283
+ raise ValueError(
284
+ f"Sparse rows for {model.__name__} cannot update non-updatable columns: "
285
+ f"{sorted(non_updatable_columns)}"
286
+ )
287
+ _require_existing_keys(session, table, key_columns, batch)
288
+ if not update_columns:
289
+ continue # nothing to insert or update: the existence check is all
290
+ if dialect.name == "sqlite" and not insert_missing:
291
+ conditions = [
292
+ table.c[column] == bindparam(f"key_{column}", type_=table.c[column].type)
293
+ for column in key_columns
294
+ ]
295
+ values = {
296
+ column: bindparam(f"set_{column}", type_=table.c[column].type)
297
+ for column in update_columns
298
+ }
299
+ if guard_column is not None:
300
+ conditions.append(
301
+ or_(
302
+ table.c[guard_column].is_(None),
303
+ table.c[guard_column]
304
+ < bindparam("guard_value", type_=table.c[guard_column].type),
305
+ )
306
+ )
307
+ update_statement = update(table).where(and_(*conditions)).values(values)
308
+ session.connection().execute(
309
+ update_statement,
310
+ [
311
+ {
312
+ **{f"key_{column}": row[column] for column in key_columns},
313
+ **{f"set_{column}": row[column] for column in update_columns},
314
+ **({"guard_value": row[guard_column]} if guard_column is not None else {}),
315
+ }
316
+ for row in batch
317
+ ],
318
+ )
319
+ elif dialect.name == "sqlite":
320
+ insert_statement = sqlite_insert(table)
321
+ if update_columns:
322
+ guard = None
323
+ if guard_column is not None:
324
+ guard = or_(
325
+ table.c[guard_column].is_(None),
326
+ table.c[guard_column] < insert_statement.excluded[guard_column],
327
+ )
328
+ insert_statement = insert_statement.on_conflict_do_update(
329
+ index_elements=[table.c[column] for column in key_columns],
330
+ set_={column: insert_statement.excluded[column] for column in update_columns},
331
+ where=guard,
332
+ )
333
+ else:
334
+ insert_statement = insert_statement.on_conflict_do_nothing(
335
+ index_elements=[table.c[column] for column in key_columns]
336
+ )
337
+ session.execute(
338
+ insert_statement,
339
+ _coalesce_rows(batch, key_columns, update_columns, guard_column),
340
+ )
341
+ elif dialect.name == "snowflake":
342
+ for offset in range(0, len(batch), _SNOWFLAKE_UPSERT_CHUNK_SIZE):
343
+ chunk = batch[offset : offset + _SNOWFLAKE_UPSERT_CHUNK_SIZE]
344
+ unique_rows = _coalesce_rows(chunk, key_columns, update_columns, guard_column)
345
+ snowflake_statement = _snowflake_merge_statement(
346
+ model,
347
+ dialect,
348
+ key_columns,
349
+ row_columns,
350
+ guard_column,
351
+ len(unique_rows),
352
+ insert_missing=insert_missing,
353
+ insert_only=insert_only,
354
+ )
355
+ snowflake_parameters = {
356
+ f"value_{row_index}_{column_index}": row[column]
357
+ for row_index, row in enumerate(unique_rows)
358
+ for column_index, column in enumerate(row_columns)
359
+ }
360
+ session.execute(snowflake_statement, snowflake_parameters)
361
+ session.expire_all()
362
+
363
+
364
+ def make_engine(settings: Settings, *, pool_size: int | None = None) -> Engine:
365
+ """Create the database engine from application settings.
366
+
367
+ Pooled connections are tested on checkout (``pool_pre_ping``), so a
368
+ connection the server closed while idle is replaced instead of failing the
369
+ next statement. ``pool_size`` sizes a connection pool explicitly.
370
+ """
371
+ if settings.database_url is None or not settings.database_url.get_secret_value().strip():
372
+ raise ValueError("database_url must be configured")
373
+ url = make_url(settings.database_url.get_secret_value())
374
+ if url.get_backend_name() == "sqlite" and url.database in (None, "", ":memory:"):
375
+ # An in-memory SQLite database exists per connection. Use a private
376
+ # temporary file instead, removed at exit: every connection (including
377
+ # request logging in worker threads) then sees the same database in
378
+ # its own transaction, and SQLite's file locking coordinates writers.
379
+ handle, path = tempfile.mkstemp(prefix="piloto-ai-cli-", suffix=".sqlite")
380
+ os.close(handle)
381
+ atexit.register(_remove_quietly, Path(path))
382
+ url = url.set(database=path)
383
+ pool_options: dict[str, Any] = {"pool_pre_ping": True}
384
+ if pool_size is not None:
385
+ pool_options["pool_size"] = pool_size
386
+ engine = create_engine(url, **pool_options)
387
+ if engine.dialect.name == "sqlite":
388
+ # SQLite has no attached database named after the Snowflake schema, so
389
+ # map the models' schema to SQLite's default database.
390
+ engine = engine.execution_options(schema_translate_map={SCHEMA: None})
391
+ # Imported here: run_log imports this module. Registering the run log's
392
+ # error listener before the engine is used keeps listener registration
393
+ # out of any event another thread is already dispatching on it.
394
+ from piloto_ai_cli.run_log import install_engine_listener
395
+
396
+ install_engine_listener(engine)
397
+ return engine
398
+
399
+
400
+ # One engine per database URL for the life of the process, as SQLAlchemy
401
+ # recommends: library callers such as the frontend agent then reuse pooled
402
+ # connections across calls instead of opening a new one each time.
403
+ _shared_engines: dict[str, Engine] = {}
404
+ _shared_engines_lock = threading.Lock()
405
+
406
+ MAX_CONCURRENT_RUNS = 4
407
+ """Library runs (query, attributes, save) that one process executes at once."""
408
+ _CONNECTIONS_PER_RUN = 3
409
+ """Connections one run holds at once: its run session, the payload store's
410
+ connection, and one short-lived session of the sync and enrichment steps."""
411
+ SHARED_POOL_SIZE = MAX_CONCURRENT_RUNS * _CONNECTIONS_PER_RUN + MAX_PAGES_IN_FLIGHT
412
+ """Connections the shared engine pools: every concurrent run's own, plus one
413
+ per request the process may be logging (``MAX_PAGES_IN_FLIGHT``), so no run
414
+ ever waits on the pool for a connection another run holds."""
415
+ _run_slots = threading.BoundedSemaphore(MAX_CONCURRENT_RUNS)
416
+
417
+
418
+ @contextmanager
419
+ def run_slot() -> Iterator[None]:
420
+ """Hold one of the process's ``MAX_CONCURRENT_RUNS`` run slots.
421
+
422
+ Further callers wait for a slot, so concurrent library calls never need
423
+ more connections than :data:`SHARED_POOL_SIZE`.
424
+ """
425
+ with _run_slots:
426
+ yield
427
+
428
+
429
+ def shared_engine(settings: Settings) -> Engine:
430
+ """Return the process-wide engine for the settings' database URL.
431
+
432
+ The first call for a URL creates the engine with :func:`make_engine`; later
433
+ calls with the same URL return that engine, so its connection pool is
434
+ reused. Callers must not dispose it; :func:`dispose_shared_engines` does,
435
+ once the process is done with the database.
436
+ """
437
+ if settings.database_url is None or not settings.database_url.get_secret_value().strip():
438
+ raise ValueError("database_url must be configured")
439
+ key = settings.database_url.get_secret_value()
440
+ with _shared_engines_lock:
441
+ engine = _shared_engines.get(key)
442
+ if engine is None:
443
+ engine = make_engine(settings, pool_size=SHARED_POOL_SIZE)
444
+ _shared_engines[key] = engine
445
+ return engine
446
+
447
+
448
+ def dispose_shared_engines() -> None:
449
+ """Dispose every engine :func:`shared_engine` created and forget them."""
450
+ with _shared_engines_lock:
451
+ engines = list(_shared_engines.values())
452
+ _shared_engines.clear()
453
+ for engine in engines:
454
+ engine.dispose()
455
+
456
+
457
+ def _remove_quietly(path: Path) -> None:
458
+ path.unlink(missing_ok=True)
459
+
460
+
461
+ def make_session_factory(engine: Engine) -> sessionmaker[Session]:
462
+ """Create a session factory bound to the engine."""
463
+ return sessionmaker(bind=engine, expire_on_commit=False)
464
+
465
+
466
+ def sync_extraction_config(session: Session, settings: Settings) -> None:
467
+ """Synchronize the current-extraction view's LLM key with application settings.
468
+
469
+ Uses the shared ``upsert`` path, a single INSERT ... ON CONFLICT (SQLite)
470
+ or MERGE (Snowflake), so concurrent commands can't race between a lookup
471
+ and an insert the way ``Session.merge()`` can. The statement runs at once,
472
+ so a raw-SQL read of the view in the same transaction sees the new key.
473
+ """
474
+ upsert(
475
+ session,
476
+ ExtractionConfig,
477
+ [
478
+ {
479
+ "config_id": "current",
480
+ "llm_model": settings.llm_model,
481
+ "llm_prompt_version": settings.llm_prompt_version,
482
+ }
483
+ ],
484
+ )
485
+
486
+
487
+ @contextmanager
488
+ def session_scope(session_factory: sessionmaker[Session]) -> Iterator[Session]:
489
+ """Yield a session and commit on success or roll back on failure."""
490
+ with session_factory.begin() as session:
491
+ yield session