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,217 @@
1
+ """Review extraction proposals."""
2
+
3
+ from collections.abc import Mapping, Sequence
4
+ from datetime import UTC, datetime
5
+ from decimal import Decimal
6
+ from typing import Any, Literal, cast
7
+
8
+ from sqlalchemy import (
9
+ Column,
10
+ CursorResult,
11
+ MetaData,
12
+ Numeric,
13
+ String,
14
+ Table,
15
+ exists,
16
+ select,
17
+ update,
18
+ )
19
+ from sqlalchemy.orm import Session
20
+ from sqlalchemy.sql.elements import ColumnElement
21
+
22
+ from piloto_ai_cli.errors import ReviewError
23
+ from piloto_ai_cli.schema.models import SCHEMA, Alias, Attribute, Base, UnitRule
24
+
25
+ ProposalType = Literal["alias", "unit_rule", "attribute"]
26
+ ReviewDecision = Literal["accept", "reject"]
27
+
28
+ # Schema-qualified so Snowflake reads the view in the CLI schema whatever the
29
+ # connection's current schema; SQLite maps the schema away (schema_translate_map).
30
+ _PENDING_PROPOSALS_VIEW = Table(
31
+ "v_pending_proposals",
32
+ MetaData(),
33
+ *(
34
+ Column(name, String())
35
+ for name in (
36
+ "proposal_type",
37
+ "proposal_id",
38
+ "status",
39
+ "extraction_id",
40
+ "ficha_id",
41
+ "attribute_id",
42
+ "display_name",
43
+ "kind",
44
+ "canonical_unit",
45
+ "raw_label",
46
+ "raw_unit",
47
+ "category",
48
+ )
49
+ ),
50
+ Column("factor", Numeric(24, 12)),
51
+ schema=SCHEMA,
52
+ )
53
+ _PENDING_PROPOSALS = select(_PENDING_PROPOSALS_VIEW).order_by(
54
+ _PENDING_PROPOSALS_VIEW.c.proposal_type, _PENDING_PROPOSALS_VIEW.c.proposal_id
55
+ )
56
+
57
+
58
+ def list_pending_proposals(session: Session) -> list[dict[str, object]]:
59
+ """Return pending proposals together with their extraction provenance."""
60
+ proposals = []
61
+ for row in session.execute(_PENDING_PROPOSALS).mappings():
62
+ proposal = dict(row)
63
+ factor = proposal["factor"]
64
+ if isinstance(factor, Decimal):
65
+ proposal["factor"] = str(factor)
66
+ proposals.append(proposal)
67
+ return proposals
68
+
69
+
70
+ def review_proposal(
71
+ session: Session,
72
+ proposal_type: ProposalType,
73
+ proposal_id: str,
74
+ decision: ReviewDecision,
75
+ *,
76
+ now: datetime | None = None,
77
+ ) -> None:
78
+ """Accept or reject a pending alias, unit rule, or attribute."""
79
+ model: type[Base]
80
+ proposal: Alias | UnitRule | Attribute | None
81
+ if proposal_type == "alias":
82
+ model = Alias
83
+ proposal = session.get(Alias, proposal_id)
84
+ elif proposal_type == "unit_rule":
85
+ model = UnitRule
86
+ proposal = session.get(UnitRule, proposal_id)
87
+ else:
88
+ model = Attribute
89
+ proposal = session.get(Attribute, proposal_id)
90
+
91
+ if proposal is None or proposal.status != "proposed":
92
+ raise ReviewError(f"No pending {proposal_type} proposal with id {proposal_id!r}")
93
+
94
+ _compare_and_set(
95
+ session,
96
+ model,
97
+ proposal_id,
98
+ expected=[_column(model, "status") == "proposed"],
99
+ values={
100
+ "status": "accepted" if decision == "accept" else "rejected",
101
+ "accepted_at": (now or datetime.now(UTC)) if decision == "accept" else None,
102
+ },
103
+ refusal=f"No pending {proposal_type} proposal with id {proposal_id!r}",
104
+ )
105
+
106
+
107
+ def merge_attribute(
108
+ session: Session,
109
+ attribute_id: str,
110
+ target_attribute_id: str,
111
+ *,
112
+ now: datetime | None = None,
113
+ ) -> None:
114
+ """Merge a pending or accepted attribute into an accepted root attribute."""
115
+ if attribute_id == target_attribute_id:
116
+ raise ReviewError("An attribute cannot be merged into itself")
117
+
118
+ # Serialize merges that touch either attribute before validating them: the
119
+ # compare-and-set below only guards the merged row, so two opposite merges
120
+ # (A into B, B into A) would update different rows, both pass their checks
121
+ # and persist a cycle. Locking both rows first makes the second command wait
122
+ # for the first to commit and then validate against the committed state.
123
+ _lock_attributes(session, (attribute_id, target_attribute_id))
124
+ attribute = session.get(Attribute, attribute_id)
125
+ target = session.get(Attribute, target_attribute_id)
126
+ if attribute is None or attribute.status == "rejected" or attribute.merged_into is not None:
127
+ raise ReviewError(f"Attribute {attribute_id!r} cannot be merged")
128
+ if target is None or target.status != "accepted" or target.merged_into is not None:
129
+ raise ReviewError(f"Target attribute {target_attribute_id!r} must be an accepted root")
130
+ # v_ficha_value only redirects the id; stored values keep their kind and
131
+ # unit, so a merge across kinds or canonical units would mislabel them.
132
+ if (attribute.kind, attribute.canonical_unit) != (target.kind, target.canonical_unit):
133
+ raise ReviewError(
134
+ f"Attribute {attribute_id!r} ({attribute.kind}, {attribute.canonical_unit}) "
135
+ f"cannot be merged into {target_attribute_id!r} "
136
+ f"({target.kind}, {target.canonical_unit}): kind and canonical unit must match"
137
+ )
138
+
139
+ values: dict[str, object] = {"merged_into": target_attribute_id}
140
+ if attribute.status == "proposed":
141
+ values.update(status="accepted", accepted_at=now or datetime.now(UTC))
142
+ # Re-check both sides in the same statement, so a concurrent decision
143
+ # (e.g. merging the target into this attribute) cannot be overwritten or
144
+ # turned into a cycle between the read above and this write.
145
+ table = cast(Table, Attribute.__table__)
146
+ target_row = table.alias("merge_target")
147
+ _compare_and_set(
148
+ session,
149
+ Attribute,
150
+ attribute_id,
151
+ expected=[
152
+ table.c.status == attribute.status,
153
+ table.c.merged_into.is_(None),
154
+ exists().where(
155
+ target_row.c.attribute_id == target_attribute_id,
156
+ target_row.c.status == "accepted",
157
+ target_row.c.merged_into.is_(None),
158
+ ),
159
+ ],
160
+ values=values,
161
+ refusal=(
162
+ f"Attribute {attribute_id!r} or target {target_attribute_id!r} changed "
163
+ "during the merge; review again"
164
+ ),
165
+ )
166
+
167
+
168
+ def _lock_attributes(session: Session, attribute_ids: Sequence[str]) -> None:
169
+ """Take the write lock on the attribute rows, in a fixed order, for this transaction.
170
+
171
+ A no-op UPDATE locks the rows on every dialect we run on: Snowflake has no
172
+ ``SELECT ... FOR UPDATE`` but holds DML locks until commit, and SQLite takes
173
+ the database write lock. Sorting the ids keeps two merges of the same pair
174
+ from locking in opposite orders. Cached objects are expired so the reads
175
+ that follow see what other commands committed before the lock was granted.
176
+ """
177
+ table = cast(Table, Attribute.__table__)
178
+ session.flush()
179
+ for attribute_id in sorted(set(attribute_ids)):
180
+ session.execute(
181
+ update(table)
182
+ .where(table.c.attribute_id == attribute_id)
183
+ .values(merged_into=table.c.merged_into)
184
+ )
185
+ session.expire_all()
186
+
187
+
188
+ def _column(model: type[Base], name: str) -> ColumnElement[Any]:
189
+ return cast(Table, model.__table__).c[name]
190
+
191
+
192
+ def _compare_and_set(
193
+ session: Session,
194
+ model: type[Base],
195
+ key: str,
196
+ *,
197
+ expected: Sequence[ColumnElement[bool]],
198
+ values: Mapping[str, object],
199
+ refusal: str,
200
+ ) -> None:
201
+ """Apply a review decision only if the row is still in the expected state.
202
+
203
+ Review decisions are the allowed in-place updates (data-model §1), and
204
+ unlike ``upsert()`` they must not win over a concurrent decision: the
205
+ expected state is part of the UPDATE, and no updated row means another
206
+ command decided first.
207
+ """
208
+ table = cast(Table, model.__table__)
209
+ (primary_key,) = table.primary_key.columns
210
+ session.flush()
211
+ result = cast(
212
+ CursorResult[Any],
213
+ session.execute(update(table).where(primary_key == key, *expected).values(dict(values))),
214
+ )
215
+ session.expire_all()
216
+ if result.rowcount != 1:
217
+ raise ReviewError(refusal)
piloto_ai_cli/rules.py ADDED
@@ -0,0 +1,67 @@
1
+ """Accepted-rule versioning."""
2
+
3
+ import json
4
+ from datetime import UTC, datetime
5
+ from decimal import Decimal
6
+ from hashlib import sha256
7
+
8
+ from sqlalchemy import select
9
+ from sqlalchemy.orm import Session
10
+
11
+ from piloto_ai_cli.schema.models import Alias, Attribute, UnitRule
12
+
13
+
14
+ def rule_set_version(session: Session) -> str:
15
+ """Return a stable version for the currently accepted attributes and rules."""
16
+ aliases = session.scalars(select(Alias).where(Alias.status == "accepted")).all()
17
+ unit_rules = session.scalars(select(UnitRule).where(UnitRule.status == "accepted")).all()
18
+ attributes = session.scalars(select(Attribute).where(Attribute.status == "accepted")).all()
19
+
20
+ document = {
21
+ "version": 1,
22
+ "attributes": [
23
+ {
24
+ "attribute_id": attribute.attribute_id,
25
+ "display_name": attribute.display_name,
26
+ "kind": attribute.kind,
27
+ "canonical_unit": attribute.canonical_unit,
28
+ "merged_into": attribute.merged_into,
29
+ "accepted_at": _timestamp(attribute.accepted_at),
30
+ }
31
+ for attribute in sorted(attributes, key=lambda row: row.attribute_id)
32
+ ],
33
+ "aliases": [
34
+ {
35
+ "raw_label": alias.raw_label,
36
+ "attribute_id": alias.attribute_id,
37
+ "accepted_at": _timestamp(alias.accepted_at),
38
+ }
39
+ for alias in sorted(aliases, key=lambda row: (row.raw_label, row.attribute_id))
40
+ ],
41
+ "unit_rules": [
42
+ {
43
+ "raw_unit": rule.raw_unit,
44
+ "category": rule.category,
45
+ "canonical_unit": rule.canonical_unit,
46
+ "factor": _decimal(rule.factor),
47
+ "accepted_at": _timestamp(rule.accepted_at),
48
+ }
49
+ for rule in sorted(unit_rules, key=lambda row: (row.raw_unit, row.category))
50
+ ],
51
+ }
52
+ encoded = json.dumps(
53
+ document, ensure_ascii=False, separators=(",", ":"), sort_keys=True, allow_nan=False
54
+ ).encode("utf-8")
55
+ return f"rules-v1:{sha256(encoded).hexdigest()}"
56
+
57
+
58
+ def _timestamp(value: datetime | None) -> str | None:
59
+ if value is None:
60
+ return None
61
+ if value.tzinfo is None or value.utcoffset() is None:
62
+ return value.isoformat(timespec="microseconds")
63
+ return value.astimezone(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
64
+
65
+
66
+ def _decimal(value: Decimal) -> str:
67
+ return format(value.normalize(), "f")
@@ -0,0 +1,230 @@
1
+ """Persistent lifecycle for a command run."""
2
+
3
+ import threading
4
+ import weakref
5
+ from collections.abc import Callable, Mapping
6
+ from datetime import UTC, datetime
7
+ from types import TracebackType
8
+ from typing import Any, Literal
9
+ from uuid import uuid4
10
+
11
+ from sqlalchemy import event
12
+ from sqlalchemy.engine import Connection, Engine, ExceptionContext
13
+ from sqlalchemy.orm import Session, SessionTransaction
14
+
15
+ from piloto_ai_cli.database import upsert
16
+ from piloto_ai_cli.errors import ContractError, ReviewError
17
+ from piloto_ai_cli.schema.models import RunLog as RunLogRow
18
+
19
+ Outcome = Literal["ok", "refused", "failed"]
20
+
21
+ _engine_listener_lock = threading.Lock()
22
+ # Engines that already carry the error listener, held by object identity.
23
+ # ``event.contains`` cannot answer this: SQLAlchemy keys its listener registry
24
+ # by ``id(target)``, and an entry outlives an option engine whose base engine
25
+ # still holds the listener, so a new engine that reuses that id would be
26
+ # reported as registered and silently left without the listener.
27
+ _engines_with_listener: weakref.WeakSet[Engine] = weakref.WeakSet()
28
+ # The run each attached connection belongs to, keyed by the connection object
29
+ # itself (never by ``id()``, which CPython reuses after garbage collection).
30
+ # Kept here rather than in ``Connection.info``, which a closed connection
31
+ # refuses.
32
+ _runs_by_connection: weakref.WeakKeyDictionary[Connection, RunLog] = weakref.WeakKeyDictionary()
33
+ _runs_lock = threading.Lock()
34
+
35
+
36
+ def _dispatch_handle_error(context: ExceptionContext) -> None:
37
+ """Record a failed statement's query id on the run that owns its connection.
38
+
39
+ Registered once per engine and never removed: engines are shared between
40
+ threads, and SQLAlchemy does not allow adding or removing a listener while
41
+ another thread may be dispatching that event. Runs attach themselves to
42
+ their connections instead.
43
+ """
44
+ connection = context.connection
45
+ if connection is None or context.execution_context is None:
46
+ return
47
+ with _runs_lock:
48
+ run = _runs_by_connection.get(connection)
49
+ if run is not None:
50
+ run._record_query_id(context.execution_context.cursor)
51
+
52
+
53
+ def install_engine_listener(engine: Engine) -> None:
54
+ """Register :func:`_dispatch_handle_error` on ``engine`` once."""
55
+ with _engine_listener_lock:
56
+ if engine not in _engines_with_listener:
57
+ event.listen(engine, "handle_error", _dispatch_handle_error)
58
+ _engines_with_listener.add(engine)
59
+
60
+
61
+ class RunLog:
62
+ """Track a command and the Snowflake queries executed by its session.
63
+
64
+ The session must be dedicated to this run. Opening and closing commit their
65
+ transactions; a failed or refused run rolls back uncommitted command work.
66
+ """
67
+
68
+ def __init__(self, session: Session, run_id: str, clock: Callable[[], datetime]) -> None:
69
+ self.session = session
70
+ self.run_id = run_id
71
+ self._clock = clock
72
+ self._query_ids: list[str] = []
73
+ self._connections: list[Connection] = []
74
+ self._closed = False
75
+ self._listening = False
76
+
77
+ @classmethod
78
+ def open(
79
+ cls,
80
+ session: Session,
81
+ command: str,
82
+ arguments: Mapping[str, Any],
83
+ *,
84
+ clock: Callable[[], datetime] = lambda: datetime.now(UTC),
85
+ ) -> RunLog:
86
+ """Create and commit an open run before executing command work."""
87
+ if session.in_transaction():
88
+ raise ValueError("RunLog requires a session without an active transaction")
89
+ run = cls(session, str(uuid4()), clock)
90
+ event.listen(session, "after_begin", run._after_begin)
91
+ run._listening = True
92
+ try:
93
+ upsert(
94
+ session,
95
+ RunLogRow,
96
+ [
97
+ {
98
+ "run_id": run.run_id,
99
+ "command": command,
100
+ "arguments": dict(arguments),
101
+ "started_at": clock(),
102
+ }
103
+ ],
104
+ )
105
+ session.commit()
106
+ except BaseException:
107
+ session.rollback()
108
+ run._detach()
109
+ raise
110
+ return run
111
+
112
+ def _after_begin(
113
+ self, session: Session, transaction: SessionTransaction, connection: Connection
114
+ ) -> None:
115
+ if connection not in self._connections:
116
+ self._connections.append(connection)
117
+ event.listen(connection, "after_cursor_execute", self._after_cursor_execute)
118
+ with _runs_lock:
119
+ _runs_by_connection[connection] = self
120
+ install_engine_listener(connection.engine)
121
+
122
+ def _after_cursor_execute(
123
+ self,
124
+ connection: Connection,
125
+ cursor: Any,
126
+ statement: str,
127
+ parameters: Any,
128
+ context: Any,
129
+ executemany: bool,
130
+ ) -> None:
131
+ self._record_query_id(cursor)
132
+
133
+ def _record_query_id(self, cursor: Any) -> None:
134
+ query_id = getattr(cursor, "sfqid", None)
135
+ if isinstance(query_id, str) and query_id:
136
+ self._query_ids.append(query_id)
137
+
138
+ def _detach(self) -> None:
139
+ if self._listening:
140
+ event.remove(self.session, "after_begin", self._after_begin)
141
+ self._listening = False
142
+ for connection in self._connections:
143
+ event.remove(connection, "after_cursor_execute", self._after_cursor_execute)
144
+ with _runs_lock:
145
+ if _runs_by_connection.get(connection) is self:
146
+ del _runs_by_connection[connection]
147
+ self._connections.clear()
148
+
149
+ def close(self, outcome: Outcome = "ok") -> None:
150
+ """Commit the final outcome and all query IDs collected before closing.
151
+
152
+ On ``ok`` the command's pending work is flushed first, while the query
153
+ listeners are still attached, so its query IDs are logged. If that work
154
+ cannot be flushed or committed, it is rolled back, the run is closed as
155
+ ``failed`` in a fresh transaction, and the original error propagates.
156
+ """
157
+ if self._closed:
158
+ raise RuntimeError("RunLog is already closed")
159
+ if outcome not in ("ok", "refused", "failed"):
160
+ raise ValueError(f"Invalid run outcome: {outcome!r}")
161
+ if outcome != "ok":
162
+ self.session.rollback()
163
+ else:
164
+ try:
165
+ self.session.flush()
166
+ except BaseException:
167
+ self.session.rollback()
168
+ self._close_failed_after_error()
169
+ raise
170
+ self._detach()
171
+ try:
172
+ self._write_closure(outcome)
173
+ except BaseException:
174
+ self.session.rollback()
175
+ if outcome != "failed":
176
+ self._close_failed_after_error()
177
+ raise
178
+ self._closed = True
179
+
180
+ def _write_closure(self, outcome: Outcome) -> None:
181
+ upsert(
182
+ self.session,
183
+ RunLogRow,
184
+ [
185
+ {
186
+ "run_id": self.run_id,
187
+ "finished_at": self._clock(),
188
+ "outcome": outcome,
189
+ "query_ids": list(self._query_ids),
190
+ }
191
+ ],
192
+ )
193
+ self.session.commit()
194
+
195
+ def _close_failed_after_error(self) -> None:
196
+ """Best effort: record ``failed`` without masking the error in flight."""
197
+ self._detach()
198
+ try:
199
+ self._write_closure("failed")
200
+ except Exception:
201
+ self.session.rollback()
202
+ return
203
+ self._closed = True
204
+
205
+ def __enter__(self) -> RunLog:
206
+ return self
207
+
208
+ def __exit__(
209
+ self,
210
+ exc_type: type[BaseException] | None,
211
+ exc_value: BaseException | None,
212
+ traceback: TracebackType | None,
213
+ ) -> None:
214
+ if not self._closed:
215
+ outcome: Outcome = (
216
+ "ok"
217
+ if exc_value is None
218
+ else "refused"
219
+ if isinstance(exc_value, (ContractError, ReviewError))
220
+ else "failed"
221
+ )
222
+ if exc_value is None:
223
+ self.close(outcome)
224
+ return
225
+ # The command already failed: closing is best effort, so a logging
226
+ # error never replaces the command's own exception (e.g. a refusal).
227
+ try:
228
+ self.close(outcome)
229
+ except Exception as closure_error:
230
+ exc_value.add_note(f"RunLog closure also failed: {closure_error!r}")
@@ -0,0 +1,25 @@
1
+ """SQLAlchemy schema models."""
2
+
3
+ from .contract import (
4
+ CONTRACT_SCHEMA_PATH,
5
+ CONTRACT_V1_SCHEMA,
6
+ STRUCTURAL_FIELDS,
7
+ ContractValidator,
8
+ ValidatedContract,
9
+ ValidatedPredicate,
10
+ validate_contract,
11
+ )
12
+ from .models import SCHEMA, Base, JSONDoc
13
+
14
+ __all__ = [
15
+ "Base",
16
+ "CONTRACT_SCHEMA_PATH",
17
+ "CONTRACT_V1_SCHEMA",
18
+ "ContractValidator",
19
+ "JSONDoc",
20
+ "SCHEMA",
21
+ "STRUCTURAL_FIELDS",
22
+ "ValidatedContract",
23
+ "ValidatedPredicate",
24
+ "validate_contract",
25
+ ]