Repository navigation
Expand file tree
/
Copy pathmodels.py
More file actions
437 lines (345 loc) · 12.3 KB
/
Copy pathmodels.py
File metadata and controls
437 lines (345 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""Immutable, SQL-free public models for the Lang2SQL runtime."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal
from enum import Enum
from types import MappingProxyType
from typing import Mapping, TypeAlias
class Capability(str, Enum):
QUERY = "query"
CONNECT = "connect"
REVIEW_ANY = "review_any"
class AggregateKind(str, Enum):
SUM = "sum"
AVG = "avg"
MIN = "min"
MAX = "max"
COUNT = "count"
class FilterOperation(str, Enum):
EQ = "eq"
IN = "in"
class ValueKind(str, Enum):
STRING = "string"
INTEGER = "integer"
DECIMAL = "decimal"
BOOLEAN = "boolean"
DATE = "date"
class ReviewAction(str, Enum):
DIMENSION_DISCLOSURE = "dimension_disclosure"
PUBLIC_DATA_SCOPE = "public_data_scope"
PUBLIC_GROUPED = "public_grouped"
@dataclass(frozen=True)
class CallContext:
scope: str
actor_id: str
conversation_id: str
capabilities: frozenset[Capability] = frozenset()
def __post_init__(self) -> None:
if not self.scope.strip() or not self.actor_id.strip():
raise ValueError("scope and actor_id are required")
if not self.conversation_id.strip():
raise ValueError("conversation_id is required")
try:
capabilities = frozenset(Capability(item) for item in self.capabilities)
except ValueError as exc:
raise ValueError("unsupported call capability") from exc
object.__setattr__(self, "capabilities", capabilities)
@dataclass(frozen=True, repr=False)
class ConnectionInput:
dsn: str = field(repr=False)
extras: Mapping[str, str] = field(default_factory=dict, repr=False)
def __post_init__(self) -> None:
if not self.dsn.strip():
raise ValueError("connection DSN is required")
object.__setattr__(
self,
"extras",
MappingProxyType(
{str(key): str(value) for key, value in self.extras.items()}
),
)
@dataclass(frozen=True)
class SourceRef:
source_id: str
generation: int
def __post_init__(self) -> None:
if not self.source_id or self.generation <= 0:
raise ValueError("source references require an active connection")
@dataclass(frozen=True)
class ScanSummary:
table_count: int
declared_join_count: int
blocked_column_count: int
pending_metric_count: int
pending_disclosure_count: int
execution_supported: bool
enrichment_status: str = "metadata_ready"
enriched_object_count: int = 0
enrichment_reason: str = ""
@dataclass(frozen=True)
class DimensionBinding:
dimension_id: str
phrase: str
def __post_init__(self) -> None:
if not self.dimension_id or not self.phrase.strip():
raise ValueError("dimension bindings require id and grounded phrase")
@dataclass(frozen=True, repr=False)
class LiteralInput:
kind: ValueKind
value: str = field(repr=False)
phrase: str = field(repr=False)
def __post_init__(self) -> None:
try:
kind = ValueKind(self.kind)
except ValueError as exc:
raise ValueError("unsupported literal kind") from exc
if not isinstance(self.value, str) or not isinstance(self.phrase, str):
raise ValueError("literal value and phrase must be strings")
if not self.value or not self.phrase.strip():
raise ValueError("literal value and grounded phrase are required")
object.__setattr__(self, "kind", kind)
@dataclass(frozen=True, repr=False)
class FilterInput:
dimension_id: str
dimension_phrase: str
operator: FilterOperation
values: tuple[LiteralInput, ...] = field(repr=False)
operator_phrase: str = ""
def __post_init__(self) -> None:
try:
operator = FilterOperation(self.operator)
except ValueError as exc:
raise ValueError("unsupported filter operation") from exc
values = tuple(self.values)
if not self.dimension_id or not self.dimension_phrase.strip() or not values:
raise ValueError("filters require a dimension and bound values")
if operator == FilterOperation.EQ and len(values) != 1:
raise ValueError("EQ filters require exactly one value")
if operator == FilterOperation.IN and (
len(values) > 20 or not self.operator_phrase.strip()
):
raise ValueError(
"IN filters require an operator phrase and at most 20 values"
)
object.__setattr__(self, "operator", operator)
object.__setattr__(self, "values", values)
@dataclass(frozen=True, repr=False)
class DateEndpoint:
value: str = field(repr=False)
phrase: str = field(repr=False)
def __post_init__(self) -> None:
if not self.value or not self.phrase.strip():
raise ValueError("date endpoints require a value and grounded phrase")
try:
date.fromisoformat(self.value)
except ValueError as exc:
raise ValueError("date endpoints require an ISO date") from exc
@dataclass(frozen=True, repr=False)
class DateWindowInput:
dimension_id: str
dimension_phrase: str
range_phrase: str
start: DateEndpoint = field(repr=False)
end: DateEndpoint = field(repr=False)
def __post_init__(self) -> None:
if (
not self.dimension_id
or not self.dimension_phrase.strip()
or not self.range_phrase.strip()
):
raise ValueError("date windows require a dimension and grounded range")
if date.fromisoformat(self.start.value) >= date.fromisoformat(self.end.value):
raise ValueError("date window start must precede its exclusive end")
@dataclass(frozen=True, repr=False)
class QueryDraft:
question: str
source: SourceRef
candidate_token: str = field(repr=False)
metric_id: str
metric_phrase: str
aggregate: AggregateKind
dimensions: tuple[DimensionBinding, ...] = ()
filters: tuple[FilterInput, ...] = field(default=(), repr=False)
time_window: DateWindowInput | None = field(default=None, repr=False)
unresolved_obligations: tuple[str, ...] = ()
limit: int = 100
def __post_init__(self) -> None:
if not self.question.strip() or not self.metric_id or not self.metric_phrase:
raise ValueError("question, metric_id, and metric_phrase are required")
if not isinstance(self.source, SourceRef):
raise ValueError("query drafts require a candidate source reference")
if not self.candidate_token or not all(
character.isalnum() or character in {"_", "-"}
for character in self.candidate_token
):
raise ValueError("query drafts require an opaque candidate token")
try:
aggregate = AggregateKind(self.aggregate)
except ValueError as exc:
raise ValueError("unsupported aggregate") from exc
if (
isinstance(self.limit, bool)
or not isinstance(self.limit, int)
or not 1 <= self.limit <= 1000
):
raise ValueError("limit must be between 1 and 1000")
object.__setattr__(self, "aggregate", aggregate)
object.__setattr__(self, "dimensions", tuple(self.dimensions))
object.__setattr__(self, "filters", tuple(self.filters))
object.__setattr__(
self, "unresolved_obligations", tuple(self.unresolved_obligations)
)
@dataclass(frozen=True)
class ConnectRequest:
context: CallContext
connection: ConnectionInput
@dataclass(frozen=True)
class CandidateRequest:
context: CallContext
question: str
def __post_init__(self) -> None:
if not self.question.strip():
raise ValueError("candidate discovery requires the original question")
@dataclass(frozen=True)
class MetricCandidate:
metric_id: str
label: str
grounded_phrase: str
allowed_aggregates: tuple[AggregateKind, ...]
def __post_init__(self) -> None:
if not self.metric_id or not self.label:
raise ValueError("metric candidates require id and label")
object.__setattr__(
self,
"allowed_aggregates",
tuple(AggregateKind(item) for item in self.allowed_aggregates),
)
@dataclass(frozen=True)
class DimensionCandidate:
dimension_id: str
label: str
grounded_phrase: str = ""
def __post_init__(self) -> None:
if not self.dimension_id or not self.label:
raise ValueError("dimension candidates require id and label")
@dataclass(frozen=True)
class FilterCandidate:
dimension_id: str
label: str
grounded_phrase: str
allowed_value_kinds: tuple[ValueKind, ...]
def __post_init__(self) -> None:
if not self.dimension_id or not self.label or not self.allowed_value_kinds:
raise ValueError("filter candidates require id, label, and value kinds")
object.__setattr__(
self,
"allowed_value_kinds",
tuple(ValueKind(item) for item in self.allowed_value_kinds),
)
@dataclass(frozen=True)
class TimeCandidate:
dimension_id: str
label: str
grounded_phrase: str
endpoint_kind: ValueKind = field(default=ValueKind.DATE, init=False)
def __post_init__(self) -> None:
if not self.dimension_id or not self.label:
raise ValueError("time candidates require id and label")
@dataclass(frozen=True)
class ReviewCandidate:
dimension_id: str
label: str
grounded_phrase: str
required_action: ReviewAction
def __post_init__(self) -> None:
if not self.dimension_id or not self.label:
raise ValueError("review candidates require id and label")
object.__setattr__(self, "required_action", ReviewAction(self.required_action))
@dataclass(frozen=True)
class CandidateSet:
source: SourceRef
question_sha256: str
candidate_token: str = field(repr=False)
metrics: tuple[MetricCandidate, ...]
grouping_dimensions: tuple[DimensionCandidate, ...] = ()
filter_dimensions: tuple[FilterCandidate, ...] = ()
time_dimensions: tuple[TimeCandidate, ...] = ()
review_required_dimensions: tuple[ReviewCandidate, ...] = ()
state: str = "ready"
message: str = ""
status: str = field(default="candidates", init=False)
def __post_init__(self) -> None:
for name in (
"metrics",
"grouping_dimensions",
"filter_dimensions",
"time_dimensions",
"review_required_dimensions",
):
object.__setattr__(self, name, tuple(getattr(self, name)))
@dataclass(frozen=True)
class PlanRequest:
context: CallContext
draft: QueryDraft
@dataclass(frozen=True)
class ReviewRequest:
review_id: str
kind: str
object_id: str
phrase: str
allowed_choices: tuple[str, ...]
source: SourceRef
@dataclass(frozen=True)
class FeedbackRequest:
context: CallContext
review_id: str
choice: str
@dataclass(frozen=True)
class PreparedPlan:
plan_id: str
source: SourceRef
expires_at: datetime
@dataclass(frozen=True)
class ExecuteRequest:
context: CallContext
plan: PreparedPlan
@dataclass(frozen=True)
class Connected:
source: SourceRef
scan: ScanSummary
reviews: tuple[ReviewRequest, ...] = ()
remaining_review_count: int = 0
@dataclass(frozen=True)
class PlanReady:
plan: PreparedPlan
status: str = field(default="ready", init=False)
@dataclass(frozen=True)
class ReviewRequired:
review: ReviewRequest
status: str = field(default="review_required", init=False)
@dataclass(frozen=True)
class Clarification:
code: str
message: str
status: str = field(default="clarification", init=False)
@dataclass(frozen=True)
class Blocked:
code: str
message: str
retryable: bool = False
status: str = field(default="blocked", init=False)
PlanResult: TypeAlias = PlanReady | ReviewRequired | Clarification | Blocked
@dataclass(frozen=True)
class FeedbackApplied:
applied: bool
message: str
next: PlanResult | None = None
Cell: TypeAlias = str | int | float | bool | Decimal | date | datetime | None
@dataclass(frozen=True)
class ExecutionReady:
plan_id: str
source: SourceRef
columns: tuple[str, ...]
rows: tuple[tuple[Cell, ...], ...]
status: str = field(default="ready", init=False)