purra-sqlite 1.0.0__tar.gz → 1.0.2__tar.gz
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.
- {purra_sqlite-1.0.0/src/purra_sqlite.egg-info → purra_sqlite-1.0.2}/PKG-INFO +66 -2
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/README.md +64 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/pyproject.toml +2 -2
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/src/purra_sqlite/__init__.py +169 -27
- purra_sqlite-1.0.2/src/purra_sqlite/approval_format.py +57 -0
- purra_sqlite-1.0.2/src/purra_sqlite/approvals.py +361 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/src/purra_sqlite/journal.py +5 -2
- purra_sqlite-1.0.2/src/purra_sqlite/recovery_cursor.py +43 -0
- purra_sqlite-1.0.2/src/purra_sqlite/recovery_schedule.py +89 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2/src/purra_sqlite.egg-info}/PKG-INFO +66 -2
- purra_sqlite-1.0.2/src/purra_sqlite.egg-info/SOURCES.txt +33 -0
- purra_sqlite-1.0.2/src/purra_sqlite.egg-info/requires.txt +1 -0
- purra_sqlite-1.0.2/tests/test_approval_resume.py +759 -0
- purra_sqlite-1.0.2/tests/test_approvals.py +299 -0
- purra_sqlite-1.0.2/tests/test_batch_inspection.py +26 -0
- purra_sqlite-1.0.2/tests/test_candidate_pages.py +46 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_deferred_journal.py +2 -2
- purra_sqlite-1.0.2/tests/test_host_lifecycle_script.py +36 -0
- purra_sqlite-1.0.2/tests/test_metadata_transactions.py +33 -0
- purra_sqlite-1.0.2/tests/test_model_route_resume.py +101 -0
- purra_sqlite-1.0.2/tests/test_recovery_cursor.py +80 -0
- purra_sqlite-1.0.2/tests/test_recovery_schedule.py +109 -0
- purra_sqlite-1.0.2/tests/test_worker_load.py +92 -0
- purra_sqlite-1.0.2/tests/test_worker_process.py +281 -0
- purra_sqlite-1.0.0/src/purra_sqlite.egg-info/SOURCES.txt +0 -18
- purra_sqlite-1.0.0/src/purra_sqlite.egg-info/requires.txt +0 -1
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/LICENSE +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/setup.cfg +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/src/purra_sqlite.egg-info/dependency_links.txt +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/src/purra_sqlite.egg-info/top_level.txt +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_covering_indexes.py +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_journal.py +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_metadata.py +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_root_scope.py +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_row_integrity.py +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_run_resume.py +0 -0
- {purra_sqlite-1.0.0 → purra_sqlite-1.0.2}/tests/test_sqlite.py +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: purra-sqlite
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.2
|
|
4
4
|
Summary: SQLite persistence for PurrA
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
7
7
|
Description-Content-Type: text/markdown
|
|
8
8
|
License-File: LICENSE
|
|
9
|
-
Requires-Dist: purra==1.0.
|
|
9
|
+
Requires-Dist: purra==1.0.2
|
|
10
10
|
Dynamic: license-file
|
|
11
11
|
|
|
12
12
|
# purra-sqlite · Python
|
|
@@ -165,3 +165,67 @@ attempts are separate blockers; reconciling a tool does not clear the attempt.
|
|
|
165
165
|
Permissions, complete usage, effects outside this adapter and Agent Tree ownership
|
|
166
166
|
remain unknown. `authority` is always `diagnosis_only`; execution must revalidate.
|
|
167
167
|
See the Core [inspection contract](../../../docs/integration-inspection.md).
|
|
168
|
+
|
|
169
|
+
## 1.0 approval storage foundation (unreleased)
|
|
170
|
+
|
|
171
|
+
Explicit offline v5 activation and host-authorized decision storage are available.
|
|
172
|
+
The opt-in tool-ready runtime supports Reactive, Planned and Auto Root recovery
|
|
173
|
+
with atomic claim/receipt association. Host-authorized MCP writes have deterministic
|
|
174
|
+
and controlled independent-service coverage. Child writes are unsupported; real
|
|
175
|
+
Provider, business MCP and downstream acceptance remain separate.
|
|
176
|
+
Keep production databases on their current format until the runtime integration
|
|
177
|
+
and acceptance are complete. See the [durable approval contract](../../../conformance/durable-approval.md#storage-foundation-api)
|
|
178
|
+
for activation, API methods, replay behavior and SDK format boundaries.
|
|
179
|
+
|
|
180
|
+
### Approval observations (1.0 development)
|
|
181
|
+
|
|
182
|
+
On explicitly activated v5 storage, recovery inspection adds current tool-ready
|
|
183
|
+
approval state, record count, checkpoint intent match, matching completed receipt
|
|
184
|
+
and Run-associated unknown approval claims. Reads do not expire or alter decisions.
|
|
185
|
+
Current host binding/permission checks remain unknown and required at execution.
|
|
186
|
+
Reports retain `diagnosis_only` authority and omit private approval data. Legacy v4
|
|
187
|
+
reports retain their existing shape. See the [approval inspection contract](../../../conformance/durable-approval.md#read-only-approval-inspection-implemented).
|
|
188
|
+
|
|
189
|
+
## Offline approval upgrade preflight
|
|
190
|
+
|
|
191
|
+
`await storage.inspect_approval_upgrade()` reads a consistent database snapshot and returns
|
|
192
|
+
`schemaVersion: 1`, `authority: diagnosis_only`, `storageVersion`, `targetVersion: 5`,
|
|
193
|
+
`status` (`ready`, `blocked`, `already_enabled`) and `blockers`. It does not create
|
|
194
|
+
schema objects, migrate rows, refresh decisions, or acquire a writer transaction.
|
|
195
|
+
As with other inspections, initial adapter construction is separate and can initialize
|
|
196
|
+
its normal schema. Use preflight on an already open adapter, not as a raw-file validator.
|
|
197
|
+
|
|
198
|
+
For v4, preflight validates same-SDK metadata and journals across every scope and
|
|
199
|
+
reports the first encountered foreign-SDK or unsettled-execution blocker. Corrupt
|
|
200
|
+
state and unsupported formats raise instead of reporting readiness. Results omit
|
|
201
|
+
scope names, Run IDs and stored content. `already_enabled` reports the format only,
|
|
202
|
+
not the health of all v5 execution state.
|
|
203
|
+
|
|
204
|
+
A `ready` result can become stale immediately. Stop writers, back up and use the
|
|
205
|
+
existing explicit activation method; activation repeats the checks inside its write
|
|
206
|
+
transaction. Preflight is not an upgrade permit, backup, automatic migration or
|
|
207
|
+
v5-to-v4 rollback API. Never point a validation fixture at production data.
|
|
208
|
+
|
|
209
|
+
For WAL-safe backup and restoration to a new path, see the
|
|
210
|
+
[offline upgrade procedure](../../../conformance/sqlite-upgrade.md).
|
|
211
|
+
|
|
212
|
+
## Synthetic host lifecycle check
|
|
213
|
+
|
|
214
|
+
From the repository root, run:
|
|
215
|
+
|
|
216
|
+
```sh
|
|
217
|
+
PYTHONPATH=src:integrations/sqlite/python/src .venv/bin/python \
|
|
218
|
+
integrations/sqlite/python/scripts/check_host_lifecycle.py
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
The check persists host-owned Run configuration separately, closes the first host,
|
|
222
|
+
reconstructs the request profile, current binding/scope revisions and absolute
|
|
223
|
+
approval expiry, then starts `RecoveryWorker` with a durable cursor and schedule.
|
|
224
|
+
An authenticated synthetic decision wakes the worker. The check waits for canonical
|
|
225
|
+
completion, stops the service, reopens storage, and verifies one completed receipt
|
|
226
|
+
with no claim or active lease.
|
|
227
|
+
|
|
228
|
+
This repository check imports its deterministic test host; it is not a production
|
|
229
|
+
host library. Applications must own the authenticated principal, configuration
|
|
230
|
+
registry and current resource-scope resolver. Missing or mismatched configuration
|
|
231
|
+
must fail before public resume. No Provider or MCP service is called.
|
|
@@ -154,3 +154,67 @@ attempts are separate blockers; reconciling a tool does not clear the attempt.
|
|
|
154
154
|
Permissions, complete usage, effects outside this adapter and Agent Tree ownership
|
|
155
155
|
remain unknown. `authority` is always `diagnosis_only`; execution must revalidate.
|
|
156
156
|
See the Core [inspection contract](../../../docs/integration-inspection.md).
|
|
157
|
+
|
|
158
|
+
## 1.0 approval storage foundation (unreleased)
|
|
159
|
+
|
|
160
|
+
Explicit offline v5 activation and host-authorized decision storage are available.
|
|
161
|
+
The opt-in tool-ready runtime supports Reactive, Planned and Auto Root recovery
|
|
162
|
+
with atomic claim/receipt association. Host-authorized MCP writes have deterministic
|
|
163
|
+
and controlled independent-service coverage. Child writes are unsupported; real
|
|
164
|
+
Provider, business MCP and downstream acceptance remain separate.
|
|
165
|
+
Keep production databases on their current format until the runtime integration
|
|
166
|
+
and acceptance are complete. See the [durable approval contract](../../../conformance/durable-approval.md#storage-foundation-api)
|
|
167
|
+
for activation, API methods, replay behavior and SDK format boundaries.
|
|
168
|
+
|
|
169
|
+
### Approval observations (1.0 development)
|
|
170
|
+
|
|
171
|
+
On explicitly activated v5 storage, recovery inspection adds current tool-ready
|
|
172
|
+
approval state, record count, checkpoint intent match, matching completed receipt
|
|
173
|
+
and Run-associated unknown approval claims. Reads do not expire or alter decisions.
|
|
174
|
+
Current host binding/permission checks remain unknown and required at execution.
|
|
175
|
+
Reports retain `diagnosis_only` authority and omit private approval data. Legacy v4
|
|
176
|
+
reports retain their existing shape. See the [approval inspection contract](../../../conformance/durable-approval.md#read-only-approval-inspection-implemented).
|
|
177
|
+
|
|
178
|
+
## Offline approval upgrade preflight
|
|
179
|
+
|
|
180
|
+
`await storage.inspect_approval_upgrade()` reads a consistent database snapshot and returns
|
|
181
|
+
`schemaVersion: 1`, `authority: diagnosis_only`, `storageVersion`, `targetVersion: 5`,
|
|
182
|
+
`status` (`ready`, `blocked`, `already_enabled`) and `blockers`. It does not create
|
|
183
|
+
schema objects, migrate rows, refresh decisions, or acquire a writer transaction.
|
|
184
|
+
As with other inspections, initial adapter construction is separate and can initialize
|
|
185
|
+
its normal schema. Use preflight on an already open adapter, not as a raw-file validator.
|
|
186
|
+
|
|
187
|
+
For v4, preflight validates same-SDK metadata and journals across every scope and
|
|
188
|
+
reports the first encountered foreign-SDK or unsettled-execution blocker. Corrupt
|
|
189
|
+
state and unsupported formats raise instead of reporting readiness. Results omit
|
|
190
|
+
scope names, Run IDs and stored content. `already_enabled` reports the format only,
|
|
191
|
+
not the health of all v5 execution state.
|
|
192
|
+
|
|
193
|
+
A `ready` result can become stale immediately. Stop writers, back up and use the
|
|
194
|
+
existing explicit activation method; activation repeats the checks inside its write
|
|
195
|
+
transaction. Preflight is not an upgrade permit, backup, automatic migration or
|
|
196
|
+
v5-to-v4 rollback API. Never point a validation fixture at production data.
|
|
197
|
+
|
|
198
|
+
For WAL-safe backup and restoration to a new path, see the
|
|
199
|
+
[offline upgrade procedure](../../../conformance/sqlite-upgrade.md).
|
|
200
|
+
|
|
201
|
+
## Synthetic host lifecycle check
|
|
202
|
+
|
|
203
|
+
From the repository root, run:
|
|
204
|
+
|
|
205
|
+
```sh
|
|
206
|
+
PYTHONPATH=src:integrations/sqlite/python/src .venv/bin/python \
|
|
207
|
+
integrations/sqlite/python/scripts/check_host_lifecycle.py
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
The check persists host-owned Run configuration separately, closes the first host,
|
|
211
|
+
reconstructs the request profile, current binding/scope revisions and absolute
|
|
212
|
+
approval expiry, then starts `RecoveryWorker` with a durable cursor and schedule.
|
|
213
|
+
An authenticated synthetic decision wakes the worker. The check waits for canonical
|
|
214
|
+
completion, stops the service, reopens storage, and verifies one completed receipt
|
|
215
|
+
with no claim or active lease.
|
|
216
|
+
|
|
217
|
+
This repository check imports its deterministic test host; it is not a production
|
|
218
|
+
host library. Applications must own the authenticated principal, configuration
|
|
219
|
+
registry and current resource-scope resolver. Missing or mismatched configuration
|
|
220
|
+
must fail before public resume. No Provider or MCP service is called.
|
|
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "purra-sqlite"
|
|
7
|
-
version = "1.0.
|
|
7
|
+
version = "1.0.2"
|
|
8
8
|
description = "SQLite persistence for PurrA"
|
|
9
9
|
requires-python = ">=3.11"
|
|
10
|
-
dependencies = ["purra==1.0.
|
|
10
|
+
dependencies = ["purra==1.0.2"]
|
|
11
11
|
readme = "README.md"
|
|
12
12
|
license = "MIT"
|
|
13
13
|
|
|
@@ -8,11 +8,12 @@ import sqlite3
|
|
|
8
8
|
import time
|
|
9
9
|
from uuid import uuid4
|
|
10
10
|
|
|
11
|
-
from purra.storage import StorageSession, STORAGE_PORT_METHODS
|
|
11
|
+
from purra.storage import StorageMetadataCache, StorageSession, STORAGE_PORT_METHODS
|
|
12
12
|
from purra.contracts import ToolHandlerResult, RunExecutionLease, RunStatus
|
|
13
13
|
from purra.execution.ownership import execution_owner, execution_claim
|
|
14
14
|
from purra.errors import ContractViolationError
|
|
15
|
-
from .journal import
|
|
15
|
+
from .journal import OutputJournal
|
|
16
|
+
from .approval_format import storage_version, enable_approvals, inspect_approval_upgrade
|
|
16
17
|
|
|
17
18
|
|
|
18
19
|
_READ_METHODS = {
|
|
@@ -84,7 +85,15 @@ class _Idempotency:
|
|
|
84
85
|
|
|
85
86
|
async def execute_once(self, run_id, tool_call, operation):
|
|
86
87
|
key = (run_id, tool_call.id)
|
|
88
|
+
approval_record = None
|
|
89
|
+
approval_claim = None
|
|
87
90
|
async with self.store._transaction(with_journal=False) as adapters:
|
|
91
|
+
if storage_version(self.store._db) == 5 and self.store._db.execute(
|
|
92
|
+
"SELECT 1 FROM purra_approvals WHERE scope=? AND sdk='python' AND run_id=? AND call_id=?", (self.store.scope, run_id, tool_call.id)
|
|
93
|
+
).fetchone():
|
|
94
|
+
from .approvals import SqliteApprovalStore
|
|
95
|
+
gate = SqliteApprovalStore(self.store, authorize=lambda *_: False)
|
|
96
|
+
approval_record = await gate._dispatch_record(adapters, run_id, tool_call)
|
|
88
97
|
receipt = adapters.get_tool_receipt(key)
|
|
89
98
|
if receipt is not None:
|
|
90
99
|
if receipt[0] != tool_call: raise ValueError("tool_idempotency_conflict")
|
|
@@ -93,10 +102,23 @@ class _Idempotency:
|
|
|
93
102
|
if claimed is not None:
|
|
94
103
|
raise ContractViolationError("Reconcile the previous tool attempt before retrying", code="tool_effect_unknown")
|
|
95
104
|
self.store._claims[key] = tool_call
|
|
105
|
+
if approval_record is not None:
|
|
106
|
+
lease = adapters.leases[run_id]
|
|
107
|
+
approval_claim = {"intentDigest": approval_record.intent.digest, "state": "claimed", "effectState": "unknown",
|
|
108
|
+
"approvalRevision": approval_record.decision_audit["revision"], "leaseOwnerId": lease.owner_id, "leaseEpoch": lease.attempt}
|
|
109
|
+
adapters.extra.setdefault("approvalExecutions", {})[approval_record.approval_id] = dict(approval_claim)
|
|
96
110
|
# External work is never performed while holding a SQLite transaction.
|
|
97
111
|
result = await operation()
|
|
98
112
|
if not isinstance(result, ToolHandlerResult): raise TypeError("invalid tool result")
|
|
113
|
+
if approval_record is not None and result.effect_state.value == "unknown":
|
|
114
|
+
raise ContractViolationError("The approved tool effect is unknown", code="tool_effect_unknown")
|
|
99
115
|
async with self.store._transaction(with_journal=False) as adapters:
|
|
116
|
+
if approval_record is not None:
|
|
117
|
+
gate._require_owner(adapters, run_id)
|
|
118
|
+
association = adapters.extra.get("approvalExecutions", {}).get(approval_record.approval_id)
|
|
119
|
+
if association != approval_claim:
|
|
120
|
+
raise ContractViolationError("Approval claim conflicts", code="approval_claim_conflict")
|
|
121
|
+
association.update(state="complete", effectState=result.effect_state.value)
|
|
100
122
|
adapters.save_tool_receipt(key, tool_call, result)
|
|
101
123
|
del self.store._claims[key]
|
|
102
124
|
return result
|
|
@@ -116,15 +138,17 @@ class SqliteAgentAdapters:
|
|
|
116
138
|
except FileExistsError: pass
|
|
117
139
|
self._lock = asyncio.Lock()
|
|
118
140
|
self._db = sqlite3.connect(path, timeout=0, isolation_level=None)
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
141
|
+
try:
|
|
142
|
+
storage_version(self._db)
|
|
143
|
+
except BaseException:
|
|
144
|
+
self._db.close()
|
|
145
|
+
raise
|
|
123
146
|
self._db.execute("PRAGMA journal_mode=WAL")
|
|
124
147
|
self._db.execute("PRAGMA synchronous=FULL")
|
|
125
148
|
self._db.execute("PRAGMA foreign_keys=ON")
|
|
126
149
|
self._db.execute("CREATE TABLE IF NOT EXISTS purra_state (scope TEXT NOT NULL, sdk TEXT NOT NULL, version INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY(scope,sdk))")
|
|
127
150
|
self._journal = OutputJournal(self._db, scope)
|
|
151
|
+
self._metadata_cache = StorageMetadataCache()
|
|
128
152
|
self._claims = {}
|
|
129
153
|
self._leases = {}
|
|
130
154
|
self.extra = {}
|
|
@@ -147,6 +171,19 @@ class SqliteAgentAdapters:
|
|
|
147
171
|
def transaction(self):
|
|
148
172
|
return self._transaction()
|
|
149
173
|
|
|
174
|
+
async def inspect_approval_upgrade(self):
|
|
175
|
+
"""Read-only v4-to-v5 readiness; activation rechecks under a writer lock."""
|
|
176
|
+
async with self._connection(read_only=True):
|
|
177
|
+
return inspect_approval_upgrade(self._db)
|
|
178
|
+
|
|
179
|
+
async def enable_approvals(self):
|
|
180
|
+
"""Explicitly activate v5 while all scopes have no unsettled execution."""
|
|
181
|
+
await enable_approvals(self)
|
|
182
|
+
|
|
183
|
+
def approval_store(self, *, authorize, clock_ms=None):
|
|
184
|
+
from .approvals import SqliteApprovalStore
|
|
185
|
+
return SqliteApprovalStore(self, authorize=authorize, clock_ms=clock_ms)
|
|
186
|
+
|
|
150
187
|
@asynccontextmanager
|
|
151
188
|
async def _connection(self, *, read_only=False):
|
|
152
189
|
async with self._lock:
|
|
@@ -165,11 +202,28 @@ class SqliteAgentAdapters:
|
|
|
165
202
|
self._db.execute("ROLLBACK")
|
|
166
203
|
raise
|
|
167
204
|
|
|
205
|
+
@asynccontextmanager
|
|
206
|
+
async def _metadata_transaction(self, *, read_only=False):
|
|
207
|
+
async with self._connection(read_only=read_only):
|
|
208
|
+
version = storage_version(self._db)
|
|
209
|
+
row = self._db.execute("SELECT version,body FROM purra_state WHERE scope=? AND sdk='python'", (self.scope,)).fetchone()
|
|
210
|
+
if row and row[0] != version:
|
|
211
|
+
raise ValueError("unsupported SQLite storage version")
|
|
212
|
+
session = self._metadata_cache.open(row[1] if row else None)
|
|
213
|
+
yield session
|
|
214
|
+
if not read_only:
|
|
215
|
+
if version == 4 and session.has_tool_ready_checkpoint():
|
|
216
|
+
raise ValueError("approval_storage_not_enabled")
|
|
217
|
+
body = session.export_snapshot()
|
|
218
|
+
if row is None or row[1] != body:
|
|
219
|
+
self._db.execute("INSERT INTO purra_state VALUES(?, 'python', ?, ?) ON CONFLICT(scope,sdk) DO UPDATE SET version=excluded.version,body=excluded.body", (self.scope, version, body))
|
|
220
|
+
|
|
168
221
|
@asynccontextmanager
|
|
169
222
|
async def _transaction(self, *, read_only=False, with_journal=True, journal_run_id=None, journal_stream_id=None, lazy_journal=False):
|
|
170
223
|
async with self._connection(read_only=read_only):
|
|
224
|
+
version = storage_version(self._db)
|
|
171
225
|
row = self._db.execute("SELECT version,body FROM purra_state WHERE scope=? AND sdk='python'", (self.scope,)).fetchone()
|
|
172
|
-
if row and row[0] !=
|
|
226
|
+
if row and row[0] != version:
|
|
173
227
|
raise ValueError("unsupported SQLite storage version")
|
|
174
228
|
adapters = StorageSession(row[1] if row else None)
|
|
175
229
|
self._claims, self._leases, self.extra = adapters.claims, adapters.leases, adapters.extra
|
|
@@ -178,9 +232,11 @@ class SqliteAgentAdapters:
|
|
|
178
232
|
self._journal.restore(adapters, root_run_id=adapters.root_for_run(journal_run_id), lazy=lazy_journal)
|
|
179
233
|
yield adapters
|
|
180
234
|
if not read_only:
|
|
235
|
+
if version == 4 and adapters.has_tool_ready_checkpoint():
|
|
236
|
+
raise ValueError("approval_storage_not_enabled")
|
|
181
237
|
body = adapters.export_snapshot()
|
|
182
238
|
if row is None or row[1] != body:
|
|
183
|
-
self._db.execute("INSERT INTO purra_state VALUES(?, 'python', ?, ?) ON CONFLICT(scope,sdk) DO UPDATE SET version=excluded.version,body=excluded.body", (self.scope,
|
|
239
|
+
self._db.execute("INSERT INTO purra_state VALUES(?, 'python', ?, ?) ON CONFLICT(scope,sdk) DO UPDATE SET version=excluded.version,body=excluded.body", (self.scope, version, body))
|
|
184
240
|
if with_journal:
|
|
185
241
|
self._journal.append(adapters)
|
|
186
242
|
|
|
@@ -197,10 +253,71 @@ class SqliteAgentAdapters:
|
|
|
197
253
|
async with self._transaction(with_journal=False) as adapters:
|
|
198
254
|
key = (run_id, tool_call.id)
|
|
199
255
|
if self._claims.get(key) != tool_call: raise ValueError("tool_claim_conflict")
|
|
256
|
+
approval = None
|
|
257
|
+
if storage_version(self._db) == 5:
|
|
258
|
+
from .approvals import SqliteApprovalStore
|
|
259
|
+
row = self._db.execute("SELECT approval_id FROM purra_approvals WHERE scope=? AND sdk='python' AND run_id=? AND call_id=?", (self.scope, run_id, tool_call.id)).fetchone()
|
|
260
|
+
if row is not None:
|
|
261
|
+
approval = SqliteApprovalStore(self, authorize=lambda *_: False)._load(row[0])
|
|
262
|
+
lease = adapters.leases.get(run_id)
|
|
263
|
+
if lease is not None and lease.owner_id is not None and (lease.expires_at_ms or 0) > int(time.time() * 1000):
|
|
264
|
+
raise ValueError("approval_reconciliation_requires_idle_run")
|
|
265
|
+
if result is not None and (not isinstance(result, ToolHandlerResult) or result.effect_state.value == "unknown"):
|
|
266
|
+
raise ValueError("approval_reconciliation_requires_known_effect")
|
|
267
|
+
association = adapters.extra.get("approvalExecutions", {}).get(approval.approval_id)
|
|
268
|
+
if (not isinstance(association, dict) or association.get("intentDigest") != approval.intent.digest
|
|
269
|
+
or association.get("state") != "claimed" or association.get("effectState") != "unknown"
|
|
270
|
+
or association.get("approvalRevision") != approval.decision_audit.get("revision")):
|
|
271
|
+
raise ValueError("approval_claim_conflict")
|
|
200
272
|
if result is not None:
|
|
201
273
|
if not isinstance(result, ToolHandlerResult): raise TypeError("invalid tool result")
|
|
202
274
|
adapters.save_tool_receipt(key, tool_call, result)
|
|
275
|
+
if approval is not None:
|
|
276
|
+
association.update(state="complete", effectState=result.effect_state.value)
|
|
277
|
+
elif approval is not None:
|
|
278
|
+
del adapters.extra["approvalExecutions"][approval.approval_id]
|
|
203
279
|
del self._claims[key]
|
|
280
|
+
from .recovery_schedule import wake_recovery_schedule
|
|
281
|
+
wake_recovery_schedule(adapters.extra, run_id, existing_only=True)
|
|
282
|
+
|
|
283
|
+
async def prune_recovery_schedule(self, run_ids):
|
|
284
|
+
"""Remove hints only for supplied canonical terminal Runs."""
|
|
285
|
+
from .recovery_schedule import remove_recovery_schedule
|
|
286
|
+
removed = []
|
|
287
|
+
async with self._transaction(with_journal=False) as session:
|
|
288
|
+
for run_id in dict.fromkeys(run_ids):
|
|
289
|
+
saved = await session.runs.get(run_id)
|
|
290
|
+
if saved.status is not RunStatus.RUNNING and remove_recovery_schedule(session.extra, run_id):
|
|
291
|
+
removed.append(run_id)
|
|
292
|
+
return tuple(removed)
|
|
293
|
+
|
|
294
|
+
def recovery_cursor(self, name, *, page_size=100):
|
|
295
|
+
from .recovery_cursor import SqliteRecoveryCursor
|
|
296
|
+
return SqliteRecoveryCursor(self, name, page_size=page_size)
|
|
297
|
+
|
|
298
|
+
def recovery_schedule(self, **options):
|
|
299
|
+
from .recovery_schedule import SqliteRecoverySchedule
|
|
300
|
+
return SqliteRecoverySchedule(self, **options)
|
|
301
|
+
|
|
302
|
+
async def list_run_candidates(self, *, after_run_id=None, limit=100):
|
|
303
|
+
"""Read a bounded index page; candidates may be terminal or Child Runs."""
|
|
304
|
+
if type(limit) is not int or not 1 <= limit <= 1000:
|
|
305
|
+
raise ValueError("candidate page limit must be between 1 and 1000")
|
|
306
|
+
if after_run_id is not None and (not isinstance(after_run_id, str) or not after_run_id):
|
|
307
|
+
raise ValueError("candidate cursor must be a nonempty Run id")
|
|
308
|
+
async with self._connection(read_only=True):
|
|
309
|
+
storage_version(self._db)
|
|
310
|
+
rows = self._db.execute(
|
|
311
|
+
"SELECT run_id FROM purra_journal_runs WHERE scope=? AND sdk='python'"
|
|
312
|
+
+ (" AND run_id>?" if after_run_id is not None else "")
|
|
313
|
+
+ " ORDER BY run_id LIMIT ?",
|
|
314
|
+
(self.scope, after_run_id, limit + 1) if after_run_id is not None else (self.scope, limit + 1),
|
|
315
|
+
).fetchall()
|
|
316
|
+
ids = tuple(row[0] for row in rows[:limit])
|
|
317
|
+
if any(not isinstance(row[0], str) or not row[0] for row in rows):
|
|
318
|
+
raise ValueError("invalid Run candidate identity")
|
|
319
|
+
return {"authority": "candidate_only", "runIds": ids,
|
|
320
|
+
"nextAfterRunId": ids[-1] if len(rows) > limit else None}
|
|
204
321
|
|
|
205
322
|
async def list_running(self):
|
|
206
323
|
async with self._transaction(read_only=True, with_journal=False) as adapters:
|
|
@@ -212,26 +329,43 @@ class SqliteAgentAdapters:
|
|
|
212
329
|
expected_preset is a host-supplied *complete* effective preset snapshot.
|
|
213
330
|
Permissions and complete usage/effect coverage outside this adapter remain unknown.
|
|
214
331
|
"""
|
|
215
|
-
from purra.observability.inspection import build_recovery_inspection
|
|
216
332
|
async with self._transaction(read_only=True, with_journal=False) as adapters:
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
333
|
+
return await self._inspect_recovery_session(adapters, run_id, expected_preset)
|
|
334
|
+
|
|
335
|
+
async def inspect_recovery_many(self, run_ids):
|
|
336
|
+
"""Diagnose up to 100 requested Runs in one committed snapshot."""
|
|
337
|
+
if not isinstance(run_ids, (list, tuple)) or len(run_ids) > 100:
|
|
338
|
+
raise ValueError("inspection batch must contain at most 100 Run ids")
|
|
339
|
+
if any(not isinstance(key, str) or not key for key in run_ids):
|
|
340
|
+
raise ValueError("inspection requires nonempty Run ids")
|
|
341
|
+
if not run_ids:
|
|
342
|
+
return {}
|
|
343
|
+
async with self._transaction(read_only=True, with_journal=False) as adapters:
|
|
344
|
+
return {key: await self._inspect_recovery_session(adapters, key, None)
|
|
345
|
+
for key in dict.fromkeys(run_ids)}
|
|
346
|
+
|
|
347
|
+
async def _inspect_recovery_session(self, adapters, run_id, expected_preset):
|
|
348
|
+
from purra.observability.inspection import build_recovery_inspection
|
|
349
|
+
saved = await adapters.runs.get(run_id)
|
|
350
|
+
info = adapters.get_run_info(run_id)
|
|
351
|
+
lease = adapters.leases.get(run_id)
|
|
352
|
+
now = int(time.time() * 1000)
|
|
353
|
+
configuration = "unknown"
|
|
354
|
+
if expected_preset and saved.agent_preset_snapshot:
|
|
355
|
+
configuration = "matched" if saved.agent_preset_snapshot == expected_preset else "mismatch"
|
|
356
|
+
from .approvals import inspect_approval_state
|
|
357
|
+
return build_recovery_inspection({
|
|
358
|
+
**inspect_approval_state(self, adapters, saved, now),
|
|
359
|
+
"status": "running" if saved.status is RunStatus.RUNNING else "terminal",
|
|
360
|
+
"checkpoint": "present" if info.has_checkpoint else "missing",
|
|
361
|
+
"attemptsAfterCheckpoint": info.model_attempt_count - info.checkpoint_attempt_count if info.has_checkpoint else None,
|
|
362
|
+
"unknownToolReceipts": sum(key[0] == run_id for key in adapters.claims),
|
|
363
|
+
"receiptScope": "run",
|
|
364
|
+
"lease": "active" if lease and lease.owner_id and (lease.expires_at_ms or 0) > now else "inactive",
|
|
365
|
+
"configuration": configuration,
|
|
366
|
+
"cancellation": "requested" if saved.status is RunStatus.CANCELED or (lease and lease.cancellation_requested_at_ms is not None) else "clear",
|
|
367
|
+
"deadline": "expired" if saved.deadline_at_ms is not None and saved.deadline_at_ms <= now else "open",
|
|
368
|
+
})
|
|
235
369
|
|
|
236
370
|
def close(self):
|
|
237
371
|
if self._lock.locked(): raise RuntimeError("storage transaction is active")
|
|
@@ -258,6 +392,10 @@ class _Leases:
|
|
|
258
392
|
old = self.store._leases.get(run_id, RunExecutionLease(run_id, run.status))
|
|
259
393
|
if run.status is not RunStatus.RUNNING or old.cancellation_requested_at_ms is not None: return False
|
|
260
394
|
if old.owner_id is not None and (old.expires_at_ms or 0) > now: return False
|
|
395
|
+
from purra.agent_execution_checkpoint import AgentToolExecutionCheckpoint
|
|
396
|
+
saved = await adapters.runs.get(run_id)
|
|
397
|
+
if isinstance(saved.execution_checkpoint, AgentToolExecutionCheckpoint) and any(key[0] == run_id for key in adapters.claims):
|
|
398
|
+
raise ContractViolationError("Reconcile the approved tool effect before recovery", code="tool_effect_unknown")
|
|
261
399
|
if run.has_checkpoint and run.model_attempt_count != run.checkpoint_attempt_count:
|
|
262
400
|
raise ContractViolationError("The last model/tool attempt needs reconciliation", code="run_recovery_requires_reconciliation")
|
|
263
401
|
self.store._leases[run_id] = replace(old, owner_id=owner_id, expires_at_ms=now + lease_duration_ms, heartbeat_at_ms=now, attempt=old.attempt + 1)
|
|
@@ -268,6 +406,8 @@ class _Leases:
|
|
|
268
406
|
now = int(time.time() * 1000)
|
|
269
407
|
old = self.store._leases.get(run_id)
|
|
270
408
|
if old is None or old.owner_id != owner_id or (old.expires_at_ms or 0) <= now: return False
|
|
409
|
+
claim = execution_claim.get()
|
|
410
|
+
if claim is not None and claim[:2] == (run_id, owner_id) and claim[2] != old.attempt: return False
|
|
271
411
|
self.store._leases[run_id] = replace(old, expires_at_ms=now + lease_duration_ms, heartbeat_at_ms=now)
|
|
272
412
|
return True
|
|
273
413
|
|
|
@@ -275,6 +415,8 @@ class _Leases:
|
|
|
275
415
|
async with self.store._transaction(with_journal=False):
|
|
276
416
|
old = self.store._leases.get(run_id)
|
|
277
417
|
if old is None or old.owner_id != owner_id: return False
|
|
418
|
+
claim = execution_claim.get()
|
|
419
|
+
if claim is not None and claim[:2] == (run_id, owner_id) and claim[2] != old.attempt: return False
|
|
278
420
|
self.store._leases[run_id] = replace(old, owner_id=None, expires_at_ms=None)
|
|
279
421
|
return True
|
|
280
422
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Opt-in database-wide v5 fence; legacy-only databases stay v4."""
|
|
2
|
+
from purra.storage import StorageSession
|
|
3
|
+
from .journal import OutputJournal
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
MARKER_SDK = "purra.approvals"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def storage_version(db):
|
|
10
|
+
if not db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='purra_state'").fetchone():
|
|
11
|
+
return 4
|
|
12
|
+
marker = db.execute("SELECT version,body FROM purra_state WHERE scope='' AND sdk=?", (MARKER_SDK,)).fetchone()
|
|
13
|
+
version = 5 if marker == (5, '{}') else 4
|
|
14
|
+
if marker is not None and version != 5:
|
|
15
|
+
raise ValueError("unsupported SQLite storage version")
|
|
16
|
+
if db.execute("SELECT 1 FROM purra_state WHERE version != ? LIMIT 1", (version,)).fetchone():
|
|
17
|
+
raise ValueError("unsupported SQLite storage version")
|
|
18
|
+
return version
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _activation_blocker(db):
|
|
22
|
+
for scope, sdk, body in db.execute("SELECT scope,sdk,body FROM purra_state ORDER BY scope,sdk").fetchall():
|
|
23
|
+
if sdk != "python":
|
|
24
|
+
return "approval_activation_foreign_sdk"
|
|
25
|
+
session = StorageSession(body)
|
|
26
|
+
OutputJournal(db, scope, initialize=False).restore(session)
|
|
27
|
+
if session.has_unsettled_execution():
|
|
28
|
+
return "approval_activation_execution_pending"
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def inspect_approval_upgrade(db):
|
|
33
|
+
"""Observe upgrade readiness in the caller's read transaction; never authorize it."""
|
|
34
|
+
version = storage_version(db)
|
|
35
|
+
blocker = None if version == 5 else _activation_blocker(db)
|
|
36
|
+
return {"schemaVersion": 1, "authority": "diagnosis_only", "storageVersion": version,
|
|
37
|
+
"targetVersion": 5, "status": "already_enabled" if version == 5 else "blocked" if blocker else "ready",
|
|
38
|
+
"blockers": [] if blocker is None else [blocker]}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def enable_approvals(storage):
|
|
42
|
+
async with storage._connection():
|
|
43
|
+
if storage_version(storage._db) == 5:
|
|
44
|
+
return
|
|
45
|
+
blocker = _activation_blocker(storage._db)
|
|
46
|
+
if blocker:
|
|
47
|
+
raise ValueError(blocker)
|
|
48
|
+
storage._db.execute("UPDATE purra_state SET version=5")
|
|
49
|
+
storage._db.execute("INSERT INTO purra_state VALUES('', ?, 5, '{}')", (MARKER_SDK,))
|
|
50
|
+
storage._db.execute("""CREATE TABLE purra_approvals (
|
|
51
|
+
scope TEXT NOT NULL, sdk TEXT NOT NULL, approval_id TEXT NOT NULL,
|
|
52
|
+
run_id TEXT NOT NULL, call_id TEXT NOT NULL, body TEXT NOT NULL,
|
|
53
|
+
PRIMARY KEY(scope,sdk,approval_id), UNIQUE(scope,sdk,run_id,call_id))""")
|
|
54
|
+
for operation in ("INSERT", "UPDATE"):
|
|
55
|
+
storage._db.execute(f"""CREATE TRIGGER purra_approval_format_{operation.lower()}
|
|
56
|
+
BEFORE {operation} ON purra_state WHEN NEW.version != 5
|
|
57
|
+
BEGIN SELECT RAISE(ABORT, 'unsupported SQLite storage version'); END""")
|