umf-access 0.1.0.dev8__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.
- umf_access/__init__.py +109 -0
- umf_access/adoption.py +41 -0
- umf_access/build/__init__.py +2 -0
- umf_access/build/approximate.py +34 -0
- umf_access/build/catalog.py +1626 -0
- umf_access/build/commands.py +394 -0
- umf_access/build/pg_privileges.py +1544 -0
- umf_access/build/privileges.py +134 -0
- umf_access/build/search.py +365 -0
- umf_access/build/unity_search.py +104 -0
- umf_access/bulk.py +227 -0
- umf_access/canonical.py +23 -0
- umf_access/capture.py +410 -0
- umf_access/catalog.py +325 -0
- umf_access/codec_support.py +427 -0
- umf_access/commands.py +93 -0
- umf_access/delta_read.py +758 -0
- umf_access/dsl/__init__.py +148 -0
- umf_access/dsl/_context.py +36 -0
- umf_access/dsl/_expressions.py +625 -0
- umf_access/dsl/_joined.py +4 -0
- umf_access/dsl/_nodes.py +207 -0
- umf_access/dsl/_query.py +5559 -0
- umf_access/dsl/_selection.py +143 -0
- umf_access/dsl/navigation.py +302 -0
- umf_access/dsl/render.py +516 -0
- umf_access/dsl/search.py +343 -0
- umf_access/engine_catalog.py +563 -0
- umf_access/generated_core.py +5 -0
- umf_access/lifecycle/__init__.py +46 -0
- umf_access/lifecycle/_darwin_process_observer.c +306 -0
- umf_access/lifecycle/approval.py +366 -0
- umf_access/lifecycle/backfills.py +79 -0
- umf_access/lifecycle/catalog.py +289 -0
- umf_access/lifecycle/cli.py +231 -0
- umf_access/lifecycle/concurrent.py +196 -0
- umf_access/lifecycle/conversion_policy.py +188 -0
- umf_access/lifecycle/correspondence.py +203 -0
- umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
- umf_access/lifecycle/generation_authority_session.py +125 -0
- umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
- umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
- umf_access/lifecycle/generation_ingress.py +185 -0
- umf_access/lifecycle/generation_root_registry.py +138 -0
- umf_access/lifecycle/head.py +250 -0
- umf_access/lifecycle/head_view.py +81 -0
- umf_access/lifecycle/host.py +1183 -0
- umf_access/lifecycle/ingress_custody.py +750 -0
- umf_access/lifecycle/ingress_local_postgres.py +7990 -0
- umf_access/lifecycle/ingress_store.py +1488 -0
- umf_access/lifecycle/ledger.py +276 -0
- umf_access/lifecycle/ledger_schema.py +116 -0
- umf_access/lifecycle/mixed.py +593 -0
- umf_access/lifecycle/outcome_schema.py +136 -0
- umf_access/lifecycle/owner_approval_core.py +1810 -0
- umf_access/lifecycle/owner_authority.py +472 -0
- umf_access/lifecycle/owner_bootstrap.py +2077 -0
- umf_access/lifecycle/owner_wire.py +161 -0
- umf_access/lifecycle/phase_fence.py +52 -0
- umf_access/lifecycle/phase_policy.py +422 -0
- umf_access/lifecycle/privileges.py +145 -0
- umf_access/lifecycle/probe.py +39 -0
- umf_access/lifecycle/progress.py +497 -0
- umf_access/lifecycle/roles.py +96 -0
- umf_access/lifecycle/row_originals.py +1712 -0
- umf_access/lifecycle/row_originals_creation.py +759 -0
- umf_access/lifecycle/row_originals_receipt.py +413 -0
- umf_access/lifecycle/seeds.py +99 -0
- umf_access/lifecycle/sql_containment.py +358 -0
- umf_access/lifecycle/sql_containment_cli.py +33 -0
- umf_access/lifecycle/sql_containment_parser.py +20 -0
- umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
- umf_access/lifecycle/table_boundary.py +22 -0
- umf_access/lifecycle/target_custody_codec.py +788 -0
- umf_access/lifecycle/witness.py +72 -0
- umf_access/managed_actions.py +271 -0
- umf_access/managed_bulk.py +353 -0
- umf_access/managed_delta.py +150 -0
- umf_access/managed_support.py +166 -0
- umf_access/manifest_commands.py +278 -0
- umf_access/native_actions.py +1007 -0
- umf_access/native_program.py +570 -0
- umf_access/pages.py +125 -0
- umf_access/postgres_bulk.py +509 -0
- umf_access/postgres_read.py +1230 -0
- umf_access/postgres_search.py +639 -0
- umf_access/protocols.py +665 -0
- umf_access/py.typed +0 -0
- umf_access/related_keys.py +233 -0
- umf_access/reviewed.py +706 -0
- umf_access/search_catalog.py +122 -0
- umf_access/targets.py +312 -0
- umf_access/types.py +220 -0
- umf_access/unified/__init__.py +187 -0
- umf_access/unified/_binding.py +654 -0
- umf_access/unified/head_session.py +144 -0
- umf_access/unified/native_binding.py +143 -0
- umf_access/unified/operation_values.py +173 -0
- umf_access/unified/outcome_values.py +76 -0
- umf_access/unified/session_async.py +161 -0
- umf_access/unified/session_binding.py +108 -0
- umf_access/unified/session_policy.py +152 -0
- umf_access/unified/session_psycopg2.py +70 -0
- umf_access/unified/session_sqlalchemy.py +161 -0
- umf_access/unified/session_sync.py +148 -0
- umf_access/unified/table_reads.py +314 -0
- umf_access/unified/table_writes.py +193 -0
- umf_access/unity_search.py +312 -0
- umf_access/values.py +280 -0
- umf_access/verification.py +64 -0
- umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
- umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
- umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
- umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
- umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
"""Native same-table search: shared sync/async snapshot, admission and decoding."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
import inspect
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from datetime import timedelta
|
|
14
|
+
from decimal import Decimal
|
|
15
|
+
from typing import Any, Protocol, cast
|
|
16
|
+
|
|
17
|
+
from pydantic import TypeAdapter
|
|
18
|
+
|
|
19
|
+
from .codec_support import checked_row
|
|
20
|
+
from .dsl import Score, Scored, SearchResult
|
|
21
|
+
from .postgres_read import (
|
|
22
|
+
_ROLE,
|
|
23
|
+
ReadObligationUnmet,
|
|
24
|
+
TimedOut,
|
|
25
|
+
_catalog_fence_programs,
|
|
26
|
+
_compiled_admissions,
|
|
27
|
+
_early_relation_locks,
|
|
28
|
+
_observe_resolution,
|
|
29
|
+
_output_value,
|
|
30
|
+
_projection_admissions,
|
|
31
|
+
_snapshot_free_timeout,
|
|
32
|
+
_term_admissions,
|
|
33
|
+
native_read_admission,
|
|
34
|
+
)
|
|
35
|
+
from .reviewed import validate_list_parameters
|
|
36
|
+
from .search_catalog import SearchEntry, SearchVariant
|
|
37
|
+
from .targets import (
|
|
38
|
+
AsyncPostgresTarget,
|
|
39
|
+
PostgresConfiguration,
|
|
40
|
+
PostgresTarget,
|
|
41
|
+
TargetMismatch,
|
|
42
|
+
_milliseconds,
|
|
43
|
+
binding_digest,
|
|
44
|
+
)
|
|
45
|
+
from .types import Vector
|
|
46
|
+
from .values import validate_vector
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class SearchError(ValueError):
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class EmbedderMismatch(SearchError):
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Embedder(Protocol):
|
|
58
|
+
def identity(self) -> Mapping[str, object]: ...
|
|
59
|
+
def embed(self, texts: list[str]) -> list[Vector]: ...
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class _Hit:
|
|
64
|
+
key: tuple[Any, ...]
|
|
65
|
+
item: Any
|
|
66
|
+
score: Score
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _statement(
|
|
70
|
+
entry: SearchEntry, path: str, params: Mapping[str, object], app_schema: str
|
|
71
|
+
) -> tuple[str, tuple[object, ...]]:
|
|
72
|
+
program = entry.artifact()
|
|
73
|
+
value: Any = program
|
|
74
|
+
for part in path.strip("/").split("/"):
|
|
75
|
+
value = value[int(part)] if isinstance(value, list) else value[part]
|
|
76
|
+
slots = []
|
|
77
|
+
for parameter in value["parameters"]:
|
|
78
|
+
source = parameter["source"]
|
|
79
|
+
if "input" in source:
|
|
80
|
+
slots.append(params[source["input"]])
|
|
81
|
+
elif "appSchema" in source:
|
|
82
|
+
slots.append(app_schema)
|
|
83
|
+
elif "literal" in source:
|
|
84
|
+
literal = source["literal"]
|
|
85
|
+
if not isinstance(literal, dict) or set(literal) != {"string"}:
|
|
86
|
+
raise SearchError("unknown native search literal carrier")
|
|
87
|
+
slots.append(literal["string"])
|
|
88
|
+
else:
|
|
89
|
+
raise SearchError("unknown native search parameter source")
|
|
90
|
+
style = json.loads(entry.program.statements_json)[path]
|
|
91
|
+
return style["sql"], tuple(slots[index] for index in style["order"])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _decode(value: object, output: Mapping[str, Any]) -> object:
|
|
95
|
+
if value is None:
|
|
96
|
+
if not output["nullable"]:
|
|
97
|
+
raise SearchError("native non-null search output is null")
|
|
98
|
+
return None
|
|
99
|
+
carrier = output["carrier"]
|
|
100
|
+
try:
|
|
101
|
+
value = _output_value(value, dict(output))
|
|
102
|
+
except ReadObligationUnmet as error:
|
|
103
|
+
raise SearchError(str(error)) from error
|
|
104
|
+
if carrier in ("binary", "vector"):
|
|
105
|
+
return value
|
|
106
|
+
expected = {"string": str, "boolean": bool, "integer": int, "decimal": Decimal}.get(
|
|
107
|
+
carrier
|
|
108
|
+
)
|
|
109
|
+
if (
|
|
110
|
+
expected is None
|
|
111
|
+
or type(value) is not expected
|
|
112
|
+
or isinstance(value, Decimal)
|
|
113
|
+
and not value.is_finite()
|
|
114
|
+
):
|
|
115
|
+
raise SearchError("native search scalar carrier mismatch")
|
|
116
|
+
return value
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _hits(entry: SearchEntry, columns: tuple[str, ...], rows: list[Any]) -> list[_Hit]:
|
|
120
|
+
program = entry.artifact()
|
|
121
|
+
outputs = program["outputs"]
|
|
122
|
+
keys = program["keyOutputs"]
|
|
123
|
+
expected = tuple(v["name"] for v in outputs + keys) + ("__umf_score",)
|
|
124
|
+
if len(rows) > program["topK"]:
|
|
125
|
+
raise SearchError("native search exceeded its owner bound")
|
|
126
|
+
result = []
|
|
127
|
+
seen = set()
|
|
128
|
+
for row in rows:
|
|
129
|
+
checked = checked_row(expected, columns, row)
|
|
130
|
+
values = {v["name"]: _decode(checked[v["name"]], v) for v in outputs}
|
|
131
|
+
decoded = entry.result.model_validate(values, strict=True)
|
|
132
|
+
item = (
|
|
133
|
+
tuple(getattr(decoded, n) for n in entry.tuple_fields)
|
|
134
|
+
if entry.tuple_fields
|
|
135
|
+
else decoded
|
|
136
|
+
)
|
|
137
|
+
key_values = tuple(_decode(checked[v["name"]], v) for v in keys)
|
|
138
|
+
by_ref = {
|
|
139
|
+
(v["field"]["module"], v["field"]["element"]): value
|
|
140
|
+
for v, value in zip(keys, key_values, strict=True)
|
|
141
|
+
}
|
|
142
|
+
entry.key_model.model_validate(
|
|
143
|
+
{
|
|
144
|
+
name: by_ref[(module, field)]
|
|
145
|
+
for module, field, name in entry.key_model.UMF_FIELDS
|
|
146
|
+
},
|
|
147
|
+
strict=True,
|
|
148
|
+
)
|
|
149
|
+
if key_values in seen:
|
|
150
|
+
raise SearchError("duplicate complete search Key")
|
|
151
|
+
seen.add(key_values)
|
|
152
|
+
score_value = checked["__umf_score"]
|
|
153
|
+
if type(score_value) is not float:
|
|
154
|
+
raise SearchError("native score carrier mismatch")
|
|
155
|
+
score = Score(score_value, program["scoreKind"])
|
|
156
|
+
result.append(_Hit(key_values, item, score))
|
|
157
|
+
return result
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _finish(variant: SearchVariant, legs: list[list[_Hit]]) -> SearchResult[Any]:
|
|
161
|
+
if variant.fusion is None:
|
|
162
|
+
if len(legs) != 1:
|
|
163
|
+
raise SearchError("fusion required for multiple native legs")
|
|
164
|
+
hits = legs[0][: variant.top_k]
|
|
165
|
+
items = tuple(
|
|
166
|
+
Scored(hit.item, index + 1, hit.score) for index, hit in enumerate(hits)
|
|
167
|
+
)
|
|
168
|
+
else:
|
|
169
|
+
if variant.fusion.kind != "rrf":
|
|
170
|
+
raise SearchError("target-defined fusion requires its own native program")
|
|
171
|
+
scores: dict[tuple[Any, ...], float] = {}
|
|
172
|
+
rows: dict[tuple[Any, ...], Any] = {}
|
|
173
|
+
for leg in legs:
|
|
174
|
+
for rank, hit in enumerate(leg, 1):
|
|
175
|
+
if hit.key in rows and rows[hit.key] != hit.item:
|
|
176
|
+
raise SearchError(
|
|
177
|
+
"same-snapshot search legs disagree on the original row"
|
|
178
|
+
)
|
|
179
|
+
rows[hit.key] = hit.item
|
|
180
|
+
scores[hit.key] = scores.get(hit.key, 0.0) + 1.0 / (
|
|
181
|
+
variant.fusion.constant + rank
|
|
182
|
+
)
|
|
183
|
+
ordered = sorted(scores, key=lambda key: (-scores[key], key))[: variant.top_k]
|
|
184
|
+
items = tuple(
|
|
185
|
+
Scored(rows[key], index + 1, Score(scores[key], "rrf"))
|
|
186
|
+
for index, key in enumerate(ordered)
|
|
187
|
+
)
|
|
188
|
+
return SearchResult(
|
|
189
|
+
items,
|
|
190
|
+
0,
|
|
191
|
+
any(e.artifact()["approximate"] for e in variant.entries),
|
|
192
|
+
any(e.artifact()["partial"] for e in variant.entries),
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _metadata_programs(
|
|
197
|
+
program: Mapping[str, Any], app_schema: str
|
|
198
|
+
) -> tuple[tuple[str, dict[str, object], str], ...]:
|
|
199
|
+
obligations = program["obligations"]
|
|
200
|
+
fence = _catalog_fence_programs(program)
|
|
201
|
+
programs = [] if fence is None else [(sql, parameters, "native text-search catalog fence differs") for sql, parameters in fence[1]]
|
|
202
|
+
programs.extend([(sql, parameters, "native search source schema differs")
|
|
203
|
+
for sql, parameters in _projection_admissions(obligations, app_schema)])
|
|
204
|
+
programs.extend((sql, parameters, "native search term configuration or index differs")
|
|
205
|
+
for sql, parameters in _term_admissions(obligations, app_schema))
|
|
206
|
+
configuration = obligations.get("keywordConfiguration")
|
|
207
|
+
if configuration is not None:
|
|
208
|
+
if (
|
|
209
|
+
not isinstance(configuration, dict)
|
|
210
|
+
or configuration.get("version") != "umf.keyword-configuration/0.1"
|
|
211
|
+
or configuration.get("nativeCatalogBeforeAfter") is not True
|
|
212
|
+
or not isinstance(configuration.get("configurations"), list)
|
|
213
|
+
or len(configuration["configurations"]) != 1
|
|
214
|
+
):
|
|
215
|
+
raise TargetMismatch("native keyword configuration packet required")
|
|
216
|
+
programs.extend((sql, parameters, "native keyword configuration differs")
|
|
217
|
+
for sql, parameters in _compiled_admissions(configuration["configurations"], app_schema))
|
|
218
|
+
return tuple(programs)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _schema_admissions(program: Mapping[str, Any], app_schema: str):
|
|
222
|
+
for sql, parameters, mismatch in _metadata_programs(program, app_schema):
|
|
223
|
+
yield ("execute", sql, parameters)
|
|
224
|
+
observed = yield ("many", 2)
|
|
225
|
+
if len(observed) != 1 or len(observed[0]) != 1 or observed[0][0] is not True:
|
|
226
|
+
raise TargetMismatch(mismatch)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _filter_parameters(program: Mapping[str, Any], values: Mapping[str, object]) -> None:
|
|
230
|
+
"""Validate retained source selection descriptors before native binding."""
|
|
231
|
+
descriptors = program["request"]["selection"].get("parameters", [])
|
|
232
|
+
validate_list_parameters(descriptors, values)
|
|
233
|
+
carriers = {"string": str, "integer": int, "decimal": Decimal, "boolean": bool}
|
|
234
|
+
for descriptor in descriptors:
|
|
235
|
+
if descriptor.get("container") == "list":
|
|
236
|
+
continue
|
|
237
|
+
annotation = carriers[descriptor["carrier"]]
|
|
238
|
+
TypeAdapter(cast(Any, annotation | None if descriptor["nullable"] else annotation)).validate_python(values[descriptor["name"]], strict=True)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _program(
|
|
242
|
+
variant: SearchVariant,
|
|
243
|
+
parameters: Mapping[str, object],
|
|
244
|
+
configuration: PostgresConfiguration,
|
|
245
|
+
embedders: Mapping[str, Any],
|
|
246
|
+
deadline: float,
|
|
247
|
+
*,
|
|
248
|
+
verify_only: bool = False,
|
|
249
|
+
target_profile: str,
|
|
250
|
+
database: str,
|
|
251
|
+
):
|
|
252
|
+
prepared = []
|
|
253
|
+
for entry in variant.entries:
|
|
254
|
+
program = entry.artifact()
|
|
255
|
+
if (
|
|
256
|
+
program["target"] != target_profile
|
|
257
|
+
or binding_digest(program["binding"]) != configuration.binding_sha256
|
|
258
|
+
):
|
|
259
|
+
raise TargetMismatch("native search binding differs from configured target")
|
|
260
|
+
if program["binding"]["schema"] not in (None, configuration.app_schema):
|
|
261
|
+
raise TargetMismatch("native search schema differs")
|
|
262
|
+
params = dict(parameters)
|
|
263
|
+
if not verify_only:
|
|
264
|
+
_filter_parameters(program, params)
|
|
265
|
+
value = params[entry.query_argument]
|
|
266
|
+
if program["index"]["kind"] == "vector":
|
|
267
|
+
vector = program["index"]["vector"]
|
|
268
|
+
dimensions = vector["dimensions"]
|
|
269
|
+
if entry.embed:
|
|
270
|
+
if vector["computedBy"] != "host" or type(value) is not str:
|
|
271
|
+
raise EmbedderMismatch(
|
|
272
|
+
"host text embedding is unavailable for the selected index"
|
|
273
|
+
)
|
|
274
|
+
embedder = embedders.get(program["index"]["id"])
|
|
275
|
+
wanted = {
|
|
276
|
+
"model": vector["model"]["id"],
|
|
277
|
+
"version": vector["model"]["version"],
|
|
278
|
+
"dimensions": dimensions,
|
|
279
|
+
}
|
|
280
|
+
if embedder is None or dict(embedder.identity()) != wanted:
|
|
281
|
+
raise EmbedderMismatch("EMBEDDER_MISMATCH")
|
|
282
|
+
embedded = yield ("embed", embedder, [value])
|
|
283
|
+
if type(embedded) is not list or len(embedded) != 1:
|
|
284
|
+
raise EmbedderMismatch("EMBEDDER_MISMATCH")
|
|
285
|
+
value = embedded[0]
|
|
286
|
+
value = validate_vector(value, dimensions=dimensions)
|
|
287
|
+
if vector["metric"] == "cosine" and not any(v != 0.0 for v in value):
|
|
288
|
+
raise SearchError("undefined zero-norm cosine query")
|
|
289
|
+
params[program["queryParameter"]] = json.dumps(
|
|
290
|
+
value, separators=(",", ":"), allow_nan=False
|
|
291
|
+
)
|
|
292
|
+
else:
|
|
293
|
+
if type(value) is not str:
|
|
294
|
+
raise SearchError("plain keyword text required")
|
|
295
|
+
params[program["queryParameter"]] = value
|
|
296
|
+
# Parse the original packet before BEGIN or native search SQL.
|
|
297
|
+
_metadata_programs(program, configuration.app_schema)
|
|
298
|
+
binding = program["binding"]
|
|
299
|
+
selection = program["selectionTemplate"]
|
|
300
|
+
mode = binding.get("schemaBinding")
|
|
301
|
+
if (selection["binding"] != binding
|
|
302
|
+
or selection["obligations"].get("schemaBinding") != mode
|
|
303
|
+
or mode not in (None, "qualified", "search-path")
|
|
304
|
+
or mode is not None and ((mode == "qualified") != (binding["schema"] is not None))):
|
|
305
|
+
raise TargetMismatch("native search original schema binding context differs")
|
|
306
|
+
prepared.append((entry, program, params))
|
|
307
|
+
yield ("begin",)
|
|
308
|
+
locked = set()
|
|
309
|
+
for _, original, _ in prepared:
|
|
310
|
+
fence = _catalog_fence_programs(original)
|
|
311
|
+
if fence is not None and fence[0] not in locked:
|
|
312
|
+
yield ("catalog-fence", fence[0])
|
|
313
|
+
locked.add(fence[0])
|
|
314
|
+
relation_locks: set[str] = set()
|
|
315
|
+
for _, original, _ in prepared:
|
|
316
|
+
locks = tuple(sql for sql in original["selectionTemplate"]["lockSql"] if sql not in relation_locks)
|
|
317
|
+
yield from _early_relation_locks(original["binding"], locks, configuration.app_schema)
|
|
318
|
+
relation_locks.update(locks)
|
|
319
|
+
native_contexts = []
|
|
320
|
+
for _, original, _ in prepared:
|
|
321
|
+
mode = original["binding"].get("schemaBinding")
|
|
322
|
+
context = None
|
|
323
|
+
if mode is not None:
|
|
324
|
+
context = yield from _observe_resolution(original["binding"], configuration.app_schema, mode, database)
|
|
325
|
+
native_contexts.append(context)
|
|
326
|
+
yield (
|
|
327
|
+
"execute",
|
|
328
|
+
"SELECT pg_catalog.set_config('search_path',%s,true),pg_catalog.set_config('row_security','on',true)",
|
|
329
|
+
('pg_catalog, "' + configuration.app_schema.replace('"', '""') + '", pg_temp',),
|
|
330
|
+
)
|
|
331
|
+
original_roles = []
|
|
332
|
+
results = []
|
|
333
|
+
for entry, program, params in prepared:
|
|
334
|
+
role, _ = yield from native_read_admission(
|
|
335
|
+
program["binding"],
|
|
336
|
+
configuration.app_schema,
|
|
337
|
+
(),
|
|
338
|
+
)
|
|
339
|
+
original_roles.append(role)
|
|
340
|
+
yield from _schema_admissions(program, configuration.app_schema)
|
|
341
|
+
yield (
|
|
342
|
+
"execute",
|
|
343
|
+
*_statement(entry, "/nativeAdmission", params, configuration.app_schema),
|
|
344
|
+
)
|
|
345
|
+
observed = yield ("many", 2)
|
|
346
|
+
if observed != [(True,)]:
|
|
347
|
+
raise TargetMismatch(
|
|
348
|
+
"native search index/expression/extension correspondence refused"
|
|
349
|
+
)
|
|
350
|
+
if verify_only:
|
|
351
|
+
yield from _schema_admissions(program, configuration.app_schema)
|
|
352
|
+
continue
|
|
353
|
+
for index in range(len(program["preflights"])):
|
|
354
|
+
yield (
|
|
355
|
+
"execute",
|
|
356
|
+
*_statement(
|
|
357
|
+
entry, "/preflights/" + str(index), params, configuration.app_schema
|
|
358
|
+
),
|
|
359
|
+
)
|
|
360
|
+
checked = yield ("many", 2)
|
|
361
|
+
if checked != [(False,)]:
|
|
362
|
+
raise SearchError("native search metric domain refused")
|
|
363
|
+
yield (
|
|
364
|
+
"execute",
|
|
365
|
+
*_statement(entry, "/statement", params, configuration.app_schema),
|
|
366
|
+
)
|
|
367
|
+
columns = yield ("columns",)
|
|
368
|
+
rows = yield ("many", program["topK"] + 1)
|
|
369
|
+
yield from _schema_admissions(program, configuration.app_schema)
|
|
370
|
+
results.append(_hits(entry, columns, rows))
|
|
371
|
+
for (_, original, _), context in zip(prepared, native_contexts, strict=True):
|
|
372
|
+
if context is not None:
|
|
373
|
+
observed = yield from _observe_resolution(original["binding"], configuration.app_schema, original["binding"]["schemaBinding"], database)
|
|
374
|
+
if observed != context:
|
|
375
|
+
raise ReadObligationUnmet("native search binding context changed inside snapshot")
|
|
376
|
+
yield ("execute", _ROLE)
|
|
377
|
+
after = yield ("one",)
|
|
378
|
+
if any(role != after for role in original_roles):
|
|
379
|
+
raise ReadObligationUnmet("native search role changed inside snapshot")
|
|
380
|
+
yield ("rollback",)
|
|
381
|
+
return None if verify_only else _finish(variant, results)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
class PostgresSearchTarget(PostgresTarget):
|
|
385
|
+
def __init__(
|
|
386
|
+
self,
|
|
387
|
+
connection: Any,
|
|
388
|
+
configuration: PostgresConfiguration,
|
|
389
|
+
*,
|
|
390
|
+
embedders: Mapping[str, Embedder] | None = None,
|
|
391
|
+
search_variants: tuple[SearchVariant, ...] = (),
|
|
392
|
+
):
|
|
393
|
+
super().__init__(connection, configuration)
|
|
394
|
+
self.embedders = dict(embedders or {})
|
|
395
|
+
self.search_variants = search_variants
|
|
396
|
+
|
|
397
|
+
def _run_search(
|
|
398
|
+
self,
|
|
399
|
+
variant: SearchVariant,
|
|
400
|
+
parameters: Mapping[str, object],
|
|
401
|
+
timeout: timedelta | None,
|
|
402
|
+
verify: bool = False,
|
|
403
|
+
):
|
|
404
|
+
duration = _milliseconds(timeout, self.configuration.default_timeout) / 1000
|
|
405
|
+
deadline = time.monotonic() + duration
|
|
406
|
+
if self.connection.info.transaction_status != 0:
|
|
407
|
+
raise ReadObligationUnmet("idle search connection required")
|
|
408
|
+
if not variant.pin.matches(self.identity()):
|
|
409
|
+
raise TargetMismatch("search target identity differs")
|
|
410
|
+
program = _program(
|
|
411
|
+
variant,
|
|
412
|
+
parameters,
|
|
413
|
+
self.configuration,
|
|
414
|
+
self.embedders,
|
|
415
|
+
deadline,
|
|
416
|
+
verify_only=verify,
|
|
417
|
+
target_profile=self.profile,
|
|
418
|
+
database=self.connection.info.dbname,
|
|
419
|
+
)
|
|
420
|
+
result: Any = None
|
|
421
|
+
began = False
|
|
422
|
+
cursor: Any = None
|
|
423
|
+
try:
|
|
424
|
+
while True:
|
|
425
|
+
if time.monotonic() >= deadline:
|
|
426
|
+
raise TimedOut("search deadline expired")
|
|
427
|
+
try:
|
|
428
|
+
operation = program.send(result)
|
|
429
|
+
except StopIteration as done:
|
|
430
|
+
return done.value
|
|
431
|
+
kind = operation[0]
|
|
432
|
+
if kind == "embed":
|
|
433
|
+
result = operation[1].embed(operation[2])
|
|
434
|
+
if inspect.isawaitable(result):
|
|
435
|
+
if inspect.iscoroutine(result):
|
|
436
|
+
result.close()
|
|
437
|
+
raise EmbedderMismatch("synchronous embedder required")
|
|
438
|
+
elif kind == "begin":
|
|
439
|
+
self.connection.execute(
|
|
440
|
+
"BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"
|
|
441
|
+
)
|
|
442
|
+
began = True
|
|
443
|
+
result = None
|
|
444
|
+
elif kind in ("catalog-fence", "snapshot-free"):
|
|
445
|
+
self.connection.execute(_snapshot_free_timeout(deadline))
|
|
446
|
+
self.connection.execute(operation[1])
|
|
447
|
+
result = None
|
|
448
|
+
elif kind == "execute":
|
|
449
|
+
self.connection.execute(
|
|
450
|
+
"SELECT pg_catalog.set_config('statement_timeout',%s,true)",
|
|
451
|
+
(str(max(1, math.ceil((deadline - time.monotonic()) * 1000))),),
|
|
452
|
+
)
|
|
453
|
+
cursor = self.connection.execute(
|
|
454
|
+
operation[1], operation[2] if len(operation) > 2 else None
|
|
455
|
+
)
|
|
456
|
+
result = None
|
|
457
|
+
elif kind == "many":
|
|
458
|
+
result = cursor.fetchmany(operation[1])
|
|
459
|
+
elif kind == "one":
|
|
460
|
+
result = cursor.fetchone()
|
|
461
|
+
elif kind == "columns":
|
|
462
|
+
result = tuple(c.name for c in cursor.description)
|
|
463
|
+
elif kind == "rollback":
|
|
464
|
+
self.connection.rollback()
|
|
465
|
+
began = False
|
|
466
|
+
result = None
|
|
467
|
+
except BaseException as error:
|
|
468
|
+
if began:
|
|
469
|
+
try:
|
|
470
|
+
self.connection.rollback()
|
|
471
|
+
# Retain native failure custody across cleanup, cancellation and audit boundaries.
|
|
472
|
+
except BaseException: # noqa: BLE001
|
|
473
|
+
self.connection.close()
|
|
474
|
+
raise ReadObligationUnmet("search cleanup failed") from error
|
|
475
|
+
if getattr(error, "sqlstate", None) == "57014" or isinstance(
|
|
476
|
+
error, TimeoutError
|
|
477
|
+
):
|
|
478
|
+
raise TimedOut("search deadline expired") from error
|
|
479
|
+
raise
|
|
480
|
+
|
|
481
|
+
def verify(self) -> None:
|
|
482
|
+
if not self.search_variants:
|
|
483
|
+
raise TargetMismatch(
|
|
484
|
+
"explicit source-bound search variants required for eager verification"
|
|
485
|
+
)
|
|
486
|
+
for variant in self.search_variants:
|
|
487
|
+
self._run_search(variant, {}, None, True)
|
|
488
|
+
|
|
489
|
+
def search(
|
|
490
|
+
self,
|
|
491
|
+
variant: SearchVariant,
|
|
492
|
+
parameters: Mapping[str, object],
|
|
493
|
+
*,
|
|
494
|
+
timeout: timedelta | None = None,
|
|
495
|
+
) -> SearchResult[Any]:
|
|
496
|
+
if not variant.pin.matches(self.identity()):
|
|
497
|
+
raise TargetMismatch("search target identity differs")
|
|
498
|
+
return cast(SearchResult[Any], self._run_search(variant, parameters, timeout))
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
class AsyncPostgresSearchTarget(AsyncPostgresTarget):
|
|
502
|
+
def __init__(
|
|
503
|
+
self,
|
|
504
|
+
connection: Any,
|
|
505
|
+
configuration: PostgresConfiguration,
|
|
506
|
+
*,
|
|
507
|
+
embedders: Mapping[str, Any] | None = None,
|
|
508
|
+
search_variants: tuple[SearchVariant, ...] = (),
|
|
509
|
+
):
|
|
510
|
+
super().__init__(connection, configuration)
|
|
511
|
+
self.embedders = dict(embedders or {})
|
|
512
|
+
self.search_variants = search_variants
|
|
513
|
+
|
|
514
|
+
async def _run_search(
|
|
515
|
+
self,
|
|
516
|
+
variant: SearchVariant,
|
|
517
|
+
parameters: Mapping[str, object],
|
|
518
|
+
timeout: timedelta | None,
|
|
519
|
+
verify: bool = False,
|
|
520
|
+
):
|
|
521
|
+
duration = _milliseconds(timeout, self.configuration.default_timeout) / 1000
|
|
522
|
+
deadline = time.monotonic() + duration
|
|
523
|
+
if self.connection.info.transaction_status != 0:
|
|
524
|
+
raise ReadObligationUnmet("idle search connection required")
|
|
525
|
+
if not variant.pin.matches(self.identity()):
|
|
526
|
+
raise TargetMismatch("search target identity differs")
|
|
527
|
+
program = _program(
|
|
528
|
+
variant,
|
|
529
|
+
parameters,
|
|
530
|
+
self.configuration,
|
|
531
|
+
self.embedders,
|
|
532
|
+
deadline,
|
|
533
|
+
verify_only=verify,
|
|
534
|
+
target_profile=self.profile,
|
|
535
|
+
database=self.connection.info.dbname,
|
|
536
|
+
)
|
|
537
|
+
result: Any = None
|
|
538
|
+
began = False
|
|
539
|
+
cursor: Any = None
|
|
540
|
+
try:
|
|
541
|
+
async with asyncio.timeout(duration):
|
|
542
|
+
while True:
|
|
543
|
+
try:
|
|
544
|
+
operation = program.send(result)
|
|
545
|
+
except StopIteration as done:
|
|
546
|
+
return done.value
|
|
547
|
+
kind = operation[0]
|
|
548
|
+
if kind == "embed":
|
|
549
|
+
result = await asyncio.to_thread(
|
|
550
|
+
operation[1].embed, operation[2]
|
|
551
|
+
)
|
|
552
|
+
if inspect.isawaitable(result):
|
|
553
|
+
result = await result
|
|
554
|
+
elif kind == "begin":
|
|
555
|
+
await self.connection.execute(
|
|
556
|
+
"BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"
|
|
557
|
+
)
|
|
558
|
+
began = True
|
|
559
|
+
result = None
|
|
560
|
+
elif kind in ("catalog-fence", "snapshot-free"):
|
|
561
|
+
await self.connection.execute(_snapshot_free_timeout(deadline))
|
|
562
|
+
await self.connection.execute(operation[1])
|
|
563
|
+
result = None
|
|
564
|
+
elif kind == "execute":
|
|
565
|
+
await self.connection.execute(
|
|
566
|
+
"SELECT pg_catalog.set_config('statement_timeout',%s,true)",
|
|
567
|
+
(
|
|
568
|
+
str(
|
|
569
|
+
max(
|
|
570
|
+
1,
|
|
571
|
+
math.ceil((deadline - time.monotonic()) * 1000),
|
|
572
|
+
)
|
|
573
|
+
),
|
|
574
|
+
),
|
|
575
|
+
)
|
|
576
|
+
cursor = await self.connection.execute(
|
|
577
|
+
operation[1], operation[2] if len(operation) > 2 else None
|
|
578
|
+
)
|
|
579
|
+
result = None
|
|
580
|
+
elif kind == "many":
|
|
581
|
+
result = await cursor.fetchmany(operation[1])
|
|
582
|
+
elif kind == "one":
|
|
583
|
+
result = await cursor.fetchone()
|
|
584
|
+
elif kind == "columns":
|
|
585
|
+
result = tuple(c.name for c in cursor.description)
|
|
586
|
+
elif kind == "rollback":
|
|
587
|
+
await self.connection.rollback()
|
|
588
|
+
began = False
|
|
589
|
+
result = None
|
|
590
|
+
except BaseException as error:
|
|
591
|
+
if began:
|
|
592
|
+
|
|
593
|
+
async def cleanup():
|
|
594
|
+
async with asyncio.timeout(2):
|
|
595
|
+
await self.connection.rollback()
|
|
596
|
+
|
|
597
|
+
task = asyncio.create_task(cleanup())
|
|
598
|
+
try:
|
|
599
|
+
await asyncio.shield(task)
|
|
600
|
+
# Retain native failure custody across cleanup, cancellation and audit boundaries.
|
|
601
|
+
except BaseException: # noqa: BLE001
|
|
602
|
+
await self.connection.close()
|
|
603
|
+
raise ReadObligationUnmet("search cleanup failed") from error
|
|
604
|
+
if getattr(error, "sqlstate", None) == "57014" or isinstance(
|
|
605
|
+
error, TimeoutError
|
|
606
|
+
):
|
|
607
|
+
raise TimedOut("search deadline expired") from error
|
|
608
|
+
raise
|
|
609
|
+
|
|
610
|
+
async def verify(self) -> None:
|
|
611
|
+
if not self.search_variants:
|
|
612
|
+
raise TargetMismatch(
|
|
613
|
+
"explicit source-bound search variants required for eager verification"
|
|
614
|
+
)
|
|
615
|
+
for variant in self.search_variants:
|
|
616
|
+
await self._run_search(variant, {}, None, True)
|
|
617
|
+
|
|
618
|
+
async def search(
|
|
619
|
+
self,
|
|
620
|
+
variant: SearchVariant,
|
|
621
|
+
parameters: Mapping[str, object],
|
|
622
|
+
*,
|
|
623
|
+
timeout: timedelta | None = None,
|
|
624
|
+
) -> SearchResult[Any]:
|
|
625
|
+
if not variant.pin.matches(self.identity()):
|
|
626
|
+
raise TargetMismatch("search target identity differs")
|
|
627
|
+
return cast(
|
|
628
|
+
SearchResult[Any], await self._run_search(variant, parameters, timeout)
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
class LakebaseSearchTarget(PostgresSearchTarget):
|
|
633
|
+
kind = "lakebase"
|
|
634
|
+
profile = "lakebase18"
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
class AsyncLakebaseSearchTarget(AsyncPostgresSearchTarget):
|
|
638
|
+
kind = "lakebase"
|
|
639
|
+
profile = "lakebase18"
|