plotroom 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.
- plotroom/__init__.py +0 -0
- plotroom/__main__.py +8 -0
- plotroom/_secret_file.py +8 -0
- plotroom/adapters/__init__.py +0 -0
- plotroom/adapters/claude_desktop.py +219 -0
- plotroom/adapters/embedding_http.py +175 -0
- plotroom/adapters/github/__init__.py +337 -0
- plotroom/adapters/github/app_credential.py +209 -0
- plotroom/adapters/github/ci.py +738 -0
- plotroom/adapters/github/commit_statuses.py +63 -0
- plotroom/adapters/github/deployments.py +213 -0
- plotroom/adapters/github/details.py +867 -0
- plotroom/adapters/github/issue_details.py +368 -0
- plotroom/adapters/github/junit.py +210 -0
- plotroom/adapters/github/junit_xml.py +162 -0
- plotroom/adapters/github/kodus_review.py +347 -0
- plotroom/adapters/github/pr_details.py +192 -0
- plotroom/adapters/github/pull_comparison.py +108 -0
- plotroom/adapters/github/read.py +530 -0
- plotroom/adapters/github/ticket_tree.py +336 -0
- plotroom/adapters/mcp/__init__.py +5 -0
- plotroom/adapters/mcp/proxy.py +722 -0
- plotroom/adapters/mcp/server.py +931 -0
- plotroom/adapters/openrouter.py +151 -0
- plotroom/adapters/store_sqlite/__init__.py +6 -0
- plotroom/adapters/store_sqlite/actions_sql.py +148 -0
- plotroom/adapters/store_sqlite/asks_sql.py +153 -0
- plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
- plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
- plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
- plotroom/adapters/store_sqlite/claims_sql.py +54 -0
- plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
- plotroom/adapters/store_sqlite/github_sql.py +331 -0
- plotroom/adapters/store_sqlite/goals_sql.py +57 -0
- plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
- plotroom/adapters/store_sqlite/items_sql.py +129 -0
- plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
- plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
- plotroom/adapters/store_sqlite/migrate.py +194 -0
- plotroom/adapters/store_sqlite/migrations/env.py +36 -0
- plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
- plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
- plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
- plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
- plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
- plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
- plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
- plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
- plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
- plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
- plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
- plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
- plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
- plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
- plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
- plotroom/adapters/store_sqlite/routes_sql.py +26 -0
- plotroom/adapters/store_sqlite/search_sql.py +116 -0
- plotroom/adapters/store_sqlite/store.py +623 -0
- plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
- plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
- plotroom/adapters/switchboard.py +152 -0
- plotroom/adapters/usage_fixture.py +11 -0
- plotroom/adapters/work_items_bmad.py +256 -0
- plotroom/adapters/work_items_github_issues.py +323 -0
- plotroom/app/__init__.py +0 -0
- plotroom/app/bridge.py +162 -0
- plotroom/app/clerk_import.py +349 -0
- plotroom/app/cli.py +290 -0
- plotroom/app/clock.py +12 -0
- plotroom/app/config.py +984 -0
- plotroom/app/daemon_start.py +453 -0
- plotroom/app/lock.py +77 -0
- plotroom/app/logging.py +93 -0
- plotroom/app/portfile.py +218 -0
- plotroom/app/runtime.py +518 -0
- plotroom/app/serve.py +671 -0
- plotroom/app/session_intake.py +51 -0
- plotroom/app/sqlite_floor.py +35 -0
- plotroom/app/tokens.py +265 -0
- plotroom/core/__init__.py +0 -0
- plotroom/core/actions.py +67 -0
- plotroom/core/ask_checks.py +124 -0
- plotroom/core/asks.py +123 -0
- plotroom/core/branch_updates.py +207 -0
- plotroom/core/bridge.py +112 -0
- plotroom/core/briefs.py +83 -0
- plotroom/core/budgets.py +182 -0
- plotroom/core/catalog.py +464 -0
- plotroom/core/checklists.py +151 -0
- plotroom/core/claims.py +296 -0
- plotroom/core/clerk_import.py +379 -0
- plotroom/core/commands.py +85 -0
- plotroom/core/deploy_window.py +21 -0
- plotroom/core/envelope.py +20 -0
- plotroom/core/events.py +227 -0
- plotroom/core/github.py +306 -0
- plotroom/core/github_projection.py +310 -0
- plotroom/core/goal_language.py +374 -0
- plotroom/core/goal_projection.py +146 -0
- plotroom/core/human_queue.py +119 -0
- plotroom/core/intake.py +106 -0
- plotroom/core/kodus_review.py +53 -0
- plotroom/core/lanes.py +281 -0
- plotroom/core/ledger.py +808 -0
- plotroom/core/merge_controller.py +344 -0
- plotroom/core/merge_flakes.py +422 -0
- plotroom/core/merge_gate.py +724 -0
- plotroom/core/merge_lane.py +70 -0
- plotroom/core/merge_overlap.py +76 -0
- plotroom/core/next_items.py +60 -0
- plotroom/core/operator_goals.py +103 -0
- plotroom/core/outbox.py +70 -0
- plotroom/core/pull_overlaps.py +152 -0
- plotroom/core/reports.py +62 -0
- plotroom/core/roles.py +100 -0
- plotroom/core/routing.py +55 -0
- plotroom/core/run_reports.py +53 -0
- plotroom/core/search.py +266 -0
- plotroom/core/search_sources.py +94 -0
- plotroom/core/snapshot.py +204 -0
- plotroom/core/trigger_actions.py +89 -0
- plotroom/core/triggers.py +550 -0
- plotroom/core/unit_of_work.py +541 -0
- plotroom/core/watchers.py +35 -0
- plotroom/core/work_items.py +23 -0
- plotroom/core/writer.py +164 -0
- plotroom/ports/__init__.py +6 -0
- plotroom/ports/clock.py +12 -0
- plotroom/ports/github_write.py +72 -0
- plotroom/ports/search.py +197 -0
- plotroom/ports/session_reader.py +23 -0
- plotroom/ports/store.py +323 -0
- plotroom/ports/usage_meter.py +35 -0
- plotroom/ports/work_items.py +22 -0
- plotroom/py.typed +0 -0
- plotroom-0.1.0.dist-info/METADATA +230 -0
- plotroom-0.1.0.dist-info/RECORD +150 -0
- plotroom-0.1.0.dist-info/WHEEL +4 -0
- plotroom-0.1.0.dist-info/entry_points.txt +2 -0
- plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
"""The SQLite ``Store``: one WAL-mode file per project, opened for exactly that project (AD-4)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import sqlite3
|
|
8
|
+
from collections.abc import AsyncGenerator, Awaitable
|
|
9
|
+
from contextlib import asynccontextmanager
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
import aiosqlite
|
|
16
|
+
import sqlite_vec # pyright: ignore[reportMissingTypeStubs]
|
|
17
|
+
from alembic.runtime.migration import MigrationContext
|
|
18
|
+
from alembic.util import CommandError as AlembicError
|
|
19
|
+
from sqlalchemy import URL, Connection, event
|
|
20
|
+
from sqlalchemy.engine.interfaces import DBAPIConnection
|
|
21
|
+
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
|
|
22
|
+
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine, create_async_engine
|
|
23
|
+
from sqlalchemy.pool import ConnectionPoolEntry
|
|
24
|
+
|
|
25
|
+
from plotroom.adapters.store_sqlite import (
|
|
26
|
+
asks_sql,
|
|
27
|
+
backfill_sql,
|
|
28
|
+
budgets_sql,
|
|
29
|
+
checklists_sql,
|
|
30
|
+
embedding_sql,
|
|
31
|
+
github_sql,
|
|
32
|
+
goals_sql,
|
|
33
|
+
human_queue_sql,
|
|
34
|
+
outbox_sql,
|
|
35
|
+
triggers_sql,
|
|
36
|
+
)
|
|
37
|
+
from plotroom.adapters.store_sqlite.actions_sql import bridge_action, bridge_expiry, pending_actions
|
|
38
|
+
from plotroom.adapters.store_sqlite.claims_sql import count_claims, read_claims
|
|
39
|
+
from plotroom.adapters.store_sqlite.items_sql import (
|
|
40
|
+
first_change,
|
|
41
|
+
open_item,
|
|
42
|
+
open_items,
|
|
43
|
+
open_overlaps,
|
|
44
|
+
)
|
|
45
|
+
from plotroom.adapters.store_sqlite.lanes_sql import board_lanes, lane_counts, worker_lane
|
|
46
|
+
from plotroom.adapters.store_sqlite.ledger_sql import (
|
|
47
|
+
EVENTS_AFTER,
|
|
48
|
+
HEAD_SEQ,
|
|
49
|
+
SqliteTransaction,
|
|
50
|
+
event_from_row,
|
|
51
|
+
)
|
|
52
|
+
from plotroom.adapters.store_sqlite.migrate import (
|
|
53
|
+
ProjectMigrationError,
|
|
54
|
+
alembic_config,
|
|
55
|
+
prepare_upgrade,
|
|
56
|
+
scheduled_backup,
|
|
57
|
+
upgrade_to_head,
|
|
58
|
+
)
|
|
59
|
+
from plotroom.adapters.store_sqlite.search_sql import search_records
|
|
60
|
+
from plotroom.adapters.store_sqlite.work_items_sql import ready_work_items
|
|
61
|
+
from plotroom.core.actions import Action, QueuedAction
|
|
62
|
+
from plotroom.core.ask_checks import Ask
|
|
63
|
+
from plotroom.core.claims import Claim
|
|
64
|
+
from plotroom.core.events import Event, LedgerError
|
|
65
|
+
from plotroom.core.github import (
|
|
66
|
+
SNAPSHOT_HEALTH,
|
|
67
|
+
FetchCursor,
|
|
68
|
+
FetchRetry,
|
|
69
|
+
GitHubSummary,
|
|
70
|
+
PullRequest,
|
|
71
|
+
)
|
|
72
|
+
from plotroom.core.github_projection import ISSUE_TREE, ISSUES, GitHubResource
|
|
73
|
+
from plotroom.core.goal_projection import (
|
|
74
|
+
GoalFacts,
|
|
75
|
+
StoredGoal,
|
|
76
|
+
project_goal_facts,
|
|
77
|
+
verified_issue_projection,
|
|
78
|
+
)
|
|
79
|
+
from plotroom.core.merge_gate import GateSnapshot, load_gate_snapshot
|
|
80
|
+
from plotroom.core.next_items import Item
|
|
81
|
+
from plotroom.core.outbox import OutboxReadiness
|
|
82
|
+
from plotroom.core.search import pack_vector
|
|
83
|
+
from plotroom.core.search_sources import EVENT_KINDS
|
|
84
|
+
from plotroom.ports.search import (
|
|
85
|
+
MAX_SEARCH_LIMIT,
|
|
86
|
+
BackfillPage,
|
|
87
|
+
BackfillPosition,
|
|
88
|
+
BackfillSource,
|
|
89
|
+
EmbeddingError,
|
|
90
|
+
EmbeddingModel,
|
|
91
|
+
EmbeddingReadiness,
|
|
92
|
+
EmbeddingRevision,
|
|
93
|
+
IndexedEmbedding,
|
|
94
|
+
SearchPage,
|
|
95
|
+
SearchRecord,
|
|
96
|
+
)
|
|
97
|
+
from plotroom.ports.store import Board, Transaction
|
|
98
|
+
from plotroom.ports.work_items import WorkItem
|
|
99
|
+
|
|
100
|
+
if TYPE_CHECKING:
|
|
101
|
+
from plotroom.core.budgets import Budget
|
|
102
|
+
from plotroom.core.human_queue import Decision
|
|
103
|
+
from plotroom.core.triggers import Trigger
|
|
104
|
+
|
|
105
|
+
BEGIN_OPTION = "plotroom_begin"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def retryable_search_write_error(error: Exception) -> str | None:
|
|
109
|
+
"""Recognize recoverable SQLite write faults from their primary result codes."""
|
|
110
|
+
if isinstance(error, DBAPIError) and isinstance(error.orig, sqlite3.OperationalError):
|
|
111
|
+
# Extended result codes have the primary code in the low byte.
|
|
112
|
+
match getattr(error.orig, "sqlite_errorcode", 0) & 0xFF:
|
|
113
|
+
case sqlite3.SQLITE_BUSY:
|
|
114
|
+
return "sqlite_busy"
|
|
115
|
+
case sqlite3.SQLITE_LOCKED:
|
|
116
|
+
return "sqlite_locked"
|
|
117
|
+
case sqlite3.SQLITE_FULL:
|
|
118
|
+
return "sqlite_full"
|
|
119
|
+
case _:
|
|
120
|
+
pass
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _on_connect(dbapi_connection: DBAPIConnection, _record: ConnectionPoolEntry) -> None:
|
|
125
|
+
cursor = dbapi_connection.cursor()
|
|
126
|
+
try:
|
|
127
|
+
cursor.execute("PRAGMA journal_mode=WAL")
|
|
128
|
+
cursor.execute("PRAGMA foreign_keys=ON")
|
|
129
|
+
finally:
|
|
130
|
+
cursor.close()
|
|
131
|
+
# The driver must not open transactions on its own (it skips BEGIN before DDL); the begin
|
|
132
|
+
# hook below emits BEGIN, so a migration's schema change and its revision commit together.
|
|
133
|
+
dbapi_connection.isolation_level = None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _on_begin(connection: Connection) -> None:
|
|
137
|
+
# The writer's transactions take the write lock up front (BEGIN IMMEDIATE) through an
|
|
138
|
+
# execution option; every other connection, migrations included, begins deferred.
|
|
139
|
+
mode = connection.get_execution_options().get(BEGIN_OPTION)
|
|
140
|
+
connection.exec_driver_sql("BEGIN IMMEDIATE" if mode == "IMMEDIATE" else "BEGIN")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def _uninterrupted[T](awaitable: Awaitable[T]) -> T:
|
|
144
|
+
"""Await ``awaitable`` to completion however often this coroutine is canceled meanwhile.
|
|
145
|
+
|
|
146
|
+
A commit or rollback must not be abandoned halfway; the cancellation is raised afterwards.
|
|
147
|
+
"""
|
|
148
|
+
task = asyncio.ensure_future(awaitable)
|
|
149
|
+
canceled = False
|
|
150
|
+
while not task.done():
|
|
151
|
+
try:
|
|
152
|
+
await asyncio.shield(task)
|
|
153
|
+
except asyncio.CancelledError:
|
|
154
|
+
canceled = True
|
|
155
|
+
result = task.result()
|
|
156
|
+
if canceled:
|
|
157
|
+
raise asyncio.CancelledError
|
|
158
|
+
return result
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def _load_vector_extension(connection: AsyncConnection) -> None:
|
|
162
|
+
if connection.info.get("sqlite_vec_loaded"):
|
|
163
|
+
return
|
|
164
|
+
raw = await connection.get_raw_connection()
|
|
165
|
+
driver = raw.driver_connection
|
|
166
|
+
if not isinstance(driver, aiosqlite.Connection):
|
|
167
|
+
raise TypeError("vector search requires an aiosqlite connection")
|
|
168
|
+
await driver.enable_load_extension(True)
|
|
169
|
+
try:
|
|
170
|
+
await driver.load_extension(sqlite_vec.loadable_path())
|
|
171
|
+
finally:
|
|
172
|
+
await driver.enable_load_extension(False)
|
|
173
|
+
connection.info["sqlite_vec_loaded"] = True
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(frozen=True)
|
|
177
|
+
class SqliteEmbeddingIndex:
|
|
178
|
+
"""The writer and reader for one model in one project's database."""
|
|
179
|
+
|
|
180
|
+
_engine: AsyncEngine
|
|
181
|
+
project_id: str
|
|
182
|
+
model: EmbeddingModel
|
|
183
|
+
|
|
184
|
+
async def cursor(self) -> int:
|
|
185
|
+
async with self._engine.connect() as connection:
|
|
186
|
+
return await embedding_sql.read_cursor(connection, self.model)
|
|
187
|
+
|
|
188
|
+
async def revisions_after(self, after: int, limit: int) -> list[EmbeddingRevision]:
|
|
189
|
+
async with self._engine.connect() as connection:
|
|
190
|
+
return await embedding_sql.read_page(connection, self.model, after, limit)
|
|
191
|
+
|
|
192
|
+
async def preflight(
|
|
193
|
+
self, kinds: tuple[str, ...], text: str | None = None
|
|
194
|
+
) -> EmbeddingReadiness:
|
|
195
|
+
async with self._engine.connect() as connection:
|
|
196
|
+
return await embedding_sql.preflight(connection, self.model, kinds, text)
|
|
197
|
+
|
|
198
|
+
async def commit(
|
|
199
|
+
self, tx: Transaction, expected: int, through: int, records: tuple[IndexedEmbedding, ...]
|
|
200
|
+
) -> bool:
|
|
201
|
+
if not isinstance(tx, SqliteTransaction):
|
|
202
|
+
raise TypeError("the SQLite embedding index requires a SQLite writer transaction")
|
|
203
|
+
return await tx.commit_embedding_batch(self._engine, self.model, expected, through, records)
|
|
204
|
+
|
|
205
|
+
async def query_vector(
|
|
206
|
+
self,
|
|
207
|
+
project: str,
|
|
208
|
+
vector: tuple[float, ...],
|
|
209
|
+
limit: int,
|
|
210
|
+
*,
|
|
211
|
+
kinds: tuple[str, ...] | None = None,
|
|
212
|
+
text: str | None = None,
|
|
213
|
+
) -> SearchPage:
|
|
214
|
+
if project != self.project_id:
|
|
215
|
+
raise LedgerError("forbidden", "search is restricted to the current project")
|
|
216
|
+
if not 1 <= limit <= MAX_SEARCH_LIMIT:
|
|
217
|
+
raise LedgerError("invalid", f"search limit must be between 1 and {MAX_SEARCH_LIMIT}")
|
|
218
|
+
try:
|
|
219
|
+
query = pack_vector(vector, self.model.dimension)
|
|
220
|
+
except EmbeddingError as exc:
|
|
221
|
+
raise LedgerError("invalid", str(exc)) from exc
|
|
222
|
+
async with self._engine.connect() as connection:
|
|
223
|
+
# Loading is only needed for queries and leaves extension loading disabled again.
|
|
224
|
+
try:
|
|
225
|
+
await _uninterrupted(_load_vector_extension(connection))
|
|
226
|
+
except (sqlite3.Error, OSError, AttributeError) as exc:
|
|
227
|
+
raise LedgerError(
|
|
228
|
+
"unavailable", "SQLite vector search requires sqlite-vec"
|
|
229
|
+
) from exc
|
|
230
|
+
return await embedding_sql.query_vectors(
|
|
231
|
+
connection, self.model, query, limit, kinds, text
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class SqliteStore:
|
|
236
|
+
"""Implements ``plotroom.ports.Store`` over ``<data_dir>/<project_id>.db``."""
|
|
237
|
+
|
|
238
|
+
def __init__(self, project_id: str, data_dir: Path) -> None:
|
|
239
|
+
self._project_id = project_id
|
|
240
|
+
self.path = data_dir / f"{project_id}.db"
|
|
241
|
+
self._engine: AsyncEngine = create_async_engine(
|
|
242
|
+
URL.create("sqlite+aiosqlite", database=str(self.path))
|
|
243
|
+
)
|
|
244
|
+
event.listen(self._engine.sync_engine, "connect", _on_connect)
|
|
245
|
+
event.listen(self._engine.sync_engine, "begin", _on_begin)
|
|
246
|
+
self._writer: AsyncConnection | None = None
|
|
247
|
+
self._writing = False
|
|
248
|
+
self._backup_lock = asyncio.Lock()
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def project_id(self) -> str:
|
|
252
|
+
return self._project_id
|
|
253
|
+
|
|
254
|
+
async def migrate(self) -> None:
|
|
255
|
+
cfg = alembic_config()
|
|
256
|
+
try:
|
|
257
|
+
await _uninterrupted(asyncio.to_thread(prepare_upgrade, self.path, cfg))
|
|
258
|
+
await upgrade_to_head(self._engine, cfg)
|
|
259
|
+
except (AlembicError, OSError, SQLAlchemyError, sqlite3.Error) as exc:
|
|
260
|
+
raise ProjectMigrationError("cannot migrate the SQLite project database") from exc
|
|
261
|
+
|
|
262
|
+
async def backup(self, root: Path, retain: int) -> str:
|
|
263
|
+
async with self._backup_lock:
|
|
264
|
+
return await _uninterrupted(
|
|
265
|
+
asyncio.to_thread(scheduled_backup, self.path, root, self.project_id, retain)
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
async def revision(self) -> str | None:
|
|
269
|
+
def read(connection: Any) -> str | None:
|
|
270
|
+
return MigrationContext.configure(connection).get_current_revision()
|
|
271
|
+
|
|
272
|
+
async with self._engine.connect() as connection:
|
|
273
|
+
return await connection.run_sync(read)
|
|
274
|
+
|
|
275
|
+
@asynccontextmanager
|
|
276
|
+
async def transaction(self) -> AsyncGenerator[SqliteTransaction]:
|
|
277
|
+
"""The project's one writer transaction, on the one writer connection (AD-3).
|
|
278
|
+
|
|
279
|
+
``BEGIN IMMEDIATE``; commits when the block exits normally and rolls back on any
|
|
280
|
+
exception. Commit and rollback finish even when the caller is canceled.
|
|
281
|
+
"""
|
|
282
|
+
if self._writing:
|
|
283
|
+
raise RuntimeError("a writer transaction is already open on this store")
|
|
284
|
+
self._writing = True
|
|
285
|
+
try:
|
|
286
|
+
connection = await self._writer_connection()
|
|
287
|
+
await connection.execution_options(**{BEGIN_OPTION: "IMMEDIATE"})
|
|
288
|
+
try:
|
|
289
|
+
transaction = await connection.begin()
|
|
290
|
+
except BaseException:
|
|
291
|
+
await self._discard_writer()
|
|
292
|
+
raise
|
|
293
|
+
handle = SqliteTransaction(connection)
|
|
294
|
+
try:
|
|
295
|
+
try:
|
|
296
|
+
yield handle
|
|
297
|
+
finally:
|
|
298
|
+
handle.expire() # a retained handle must not reach the next input's transaction
|
|
299
|
+
except BaseException:
|
|
300
|
+
try:
|
|
301
|
+
await _uninterrupted(transaction.rollback())
|
|
302
|
+
except Exception:
|
|
303
|
+
await self._discard_writer()
|
|
304
|
+
raise
|
|
305
|
+
try:
|
|
306
|
+
await _uninterrupted(transaction.commit())
|
|
307
|
+
except BaseException:
|
|
308
|
+
# SQLAlchemy deactivates its transaction even if SQLite's COMMIT fails.
|
|
309
|
+
# Discard the connection to release any transaction still open in SQLite.
|
|
310
|
+
await self._discard_writer()
|
|
311
|
+
raise
|
|
312
|
+
finally:
|
|
313
|
+
self._writing = False
|
|
314
|
+
|
|
315
|
+
async def _writer_connection(self) -> AsyncConnection:
|
|
316
|
+
if self._writer is None:
|
|
317
|
+
self._writer = await self._engine.connect()
|
|
318
|
+
return self._writer
|
|
319
|
+
|
|
320
|
+
async def _discard_writer(self) -> None:
|
|
321
|
+
"""Drop a writer connection whose state is unknown; the next transaction opens a new one."""
|
|
322
|
+
connection, self._writer = self._writer, None
|
|
323
|
+
if connection is not None:
|
|
324
|
+
with contextlib.suppress(Exception):
|
|
325
|
+
await _uninterrupted(connection.invalidate())
|
|
326
|
+
with contextlib.suppress(Exception):
|
|
327
|
+
await _uninterrupted(connection.close())
|
|
328
|
+
|
|
329
|
+
async def head_seq(self) -> int:
|
|
330
|
+
async with self._engine.connect() as connection:
|
|
331
|
+
return int((await connection.execute(HEAD_SEQ)).scalar_one())
|
|
332
|
+
|
|
333
|
+
async def events_after(self, seq: int, limit: int = 100) -> list[Event]:
|
|
334
|
+
async with self._engine.connect() as connection:
|
|
335
|
+
result = await connection.execute(EVENTS_AFTER, {"seq": seq, "limit": limit})
|
|
336
|
+
return [event_from_row(row) for row in result]
|
|
337
|
+
|
|
338
|
+
async def index(self, tx: Transaction, event: Event) -> None:
|
|
339
|
+
if event.kind in EVENT_KINDS:
|
|
340
|
+
if not isinstance(tx, SqliteTransaction):
|
|
341
|
+
raise TypeError("the SQLite index requires a SQLite writer transaction")
|
|
342
|
+
await tx.index_event(self._engine, event)
|
|
343
|
+
|
|
344
|
+
async def index_record(
|
|
345
|
+
self, tx: Transaction, record: SearchRecord, *, only_if_absent: bool = False
|
|
346
|
+
) -> None:
|
|
347
|
+
if not isinstance(tx, SqliteTransaction):
|
|
348
|
+
raise TypeError("the SQLite index requires a SQLite writer transaction")
|
|
349
|
+
await tx.index_record(self._engine, record, only_if_absent=only_if_absent)
|
|
350
|
+
|
|
351
|
+
async def backfill_position(self, source: BackfillSource) -> BackfillPosition:
|
|
352
|
+
async with self._engine.connect() as connection:
|
|
353
|
+
return await backfill_sql.position(connection, source)
|
|
354
|
+
|
|
355
|
+
async def backfill_page(
|
|
356
|
+
self, source: BackfillSource, after: tuple[str | int, ...], limit: int
|
|
357
|
+
) -> BackfillPage:
|
|
358
|
+
if limit < 1:
|
|
359
|
+
raise ValueError("search backfill requires a positive page size")
|
|
360
|
+
async with self._engine.connect() as connection:
|
|
361
|
+
return await backfill_sql.read_page(connection, source, after, limit)
|
|
362
|
+
|
|
363
|
+
async def commit_backfill(
|
|
364
|
+
self,
|
|
365
|
+
tx: Transaction,
|
|
366
|
+
source: BackfillSource,
|
|
367
|
+
expected: BackfillPosition,
|
|
368
|
+
page: BackfillPage,
|
|
369
|
+
) -> bool:
|
|
370
|
+
if not isinstance(tx, SqliteTransaction):
|
|
371
|
+
raise TypeError("search backfill requires a SQLite writer transaction")
|
|
372
|
+
return await tx.commit_search_backfill(self._engine, source, expected, page)
|
|
373
|
+
|
|
374
|
+
async def query(
|
|
375
|
+
self, project: str, text: str, kinds: tuple[str, ...] | None, limit: int
|
|
376
|
+
) -> SearchPage:
|
|
377
|
+
if project != self._project_id:
|
|
378
|
+
raise LedgerError("forbidden", "search is restricted to the current project")
|
|
379
|
+
if kinds == ():
|
|
380
|
+
return SearchPage((), 0)
|
|
381
|
+
async with self._engine.connect() as connection:
|
|
382
|
+
return await search_records(connection, text, kinds, limit)
|
|
383
|
+
|
|
384
|
+
def embedding_index(self, model: EmbeddingModel) -> SqliteEmbeddingIndex:
|
|
385
|
+
return SqliteEmbeddingIndex(self._engine, self._project_id, model)
|
|
386
|
+
|
|
387
|
+
async def _board(self, connection: AsyncConnection, role: str) -> Board:
|
|
388
|
+
cursor = int((await connection.execute(HEAD_SEQ)).scalar_one())
|
|
389
|
+
return (
|
|
390
|
+
cursor,
|
|
391
|
+
await open_items(connection, role),
|
|
392
|
+
await lane_counts(connection, role),
|
|
393
|
+
await board_lanes(connection, role),
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
async def read_board(self, role: str) -> Board:
|
|
397
|
+
async with self._engine.connect() as connection:
|
|
398
|
+
return await self._board(connection, role)
|
|
399
|
+
|
|
400
|
+
async def read_snapshot(
|
|
401
|
+
self,
|
|
402
|
+
role: str,
|
|
403
|
+
repository: str | None,
|
|
404
|
+
*,
|
|
405
|
+
checklist_lane: str | None = None,
|
|
406
|
+
include_github_health: bool = False,
|
|
407
|
+
) -> tuple[Board, GitHubSummary | None, dict[str, int], int, str | None, FetchCursor | None]:
|
|
408
|
+
async with self._engine.connect() as connection:
|
|
409
|
+
board, github = (
|
|
410
|
+
(await self._board(connection, role), None)
|
|
411
|
+
if repository is None
|
|
412
|
+
else await self._github_board(connection, role, repository)
|
|
413
|
+
)
|
|
414
|
+
if checklist_lane is not None:
|
|
415
|
+
_, _, _, lanes = board
|
|
416
|
+
for index, lane in enumerate(lanes):
|
|
417
|
+
if lane.id == checklist_lane:
|
|
418
|
+
checklist = await checklists_sql.find_checklist(connection, lane.id)
|
|
419
|
+
lanes[index] = lane.with_checklist(checklist)
|
|
420
|
+
break
|
|
421
|
+
trigger_counts = await triggers_sql.trigger_counts(connection)
|
|
422
|
+
claim_count = await count_claims(connection, role)
|
|
423
|
+
freeze_reason = await SqliteTransaction(connection).deploy_freeze()
|
|
424
|
+
health = (
|
|
425
|
+
await github_sql.fetch_cursor(connection, repository, SNAPSHOT_HEALTH)
|
|
426
|
+
if include_github_health and repository is not None
|
|
427
|
+
else None
|
|
428
|
+
)
|
|
429
|
+
return board, github, trigger_counts, claim_count, freeze_reason, health
|
|
430
|
+
|
|
431
|
+
async def read_github_board(self, role: str, repository: str) -> tuple[Board, GitHubSummary]:
|
|
432
|
+
async with self._engine.connect() as connection:
|
|
433
|
+
return await self._github_board(connection, role, repository)
|
|
434
|
+
|
|
435
|
+
async def _github_board(
|
|
436
|
+
self, connection: AsyncConnection, role: str, repository: str
|
|
437
|
+
) -> tuple[Board, GitHubSummary]:
|
|
438
|
+
cursor, items, counts, lanes = await self._board(connection, role)
|
|
439
|
+
projected = await github_sql.project_lane_heads(connection, repository, lanes)
|
|
440
|
+
return (cursor, items, counts, projected), await github_sql.summary(connection, repository)
|
|
441
|
+
|
|
442
|
+
async def read_claims(
|
|
443
|
+
self, role: str, lane: str | None, offset: int, limit: int
|
|
444
|
+
) -> tuple[int, list[Claim]]:
|
|
445
|
+
async with self._engine.connect() as connection:
|
|
446
|
+
cursor = int((await connection.execute(HEAD_SEQ)).scalar_one())
|
|
447
|
+
return cursor, await read_claims(connection, role, lane, offset, limit)
|
|
448
|
+
|
|
449
|
+
async def read_brief_claims(self, worker: str) -> tuple[str | None, list[Claim]]:
|
|
450
|
+
async with self._engine.connect() as connection:
|
|
451
|
+
lane = await worker_lane(connection, worker)
|
|
452
|
+
return lane.id if lane else None, await read_claims(connection, "orchestrator")
|
|
453
|
+
|
|
454
|
+
async def read_overlaps(
|
|
455
|
+
self, role: str, lane: str | None, pr: int | None, offset: int, limit: int
|
|
456
|
+
) -> tuple[int, list[Item]]:
|
|
457
|
+
async with self._engine.connect() as connection:
|
|
458
|
+
cursor = int((await connection.execute(HEAD_SEQ)).scalar_one())
|
|
459
|
+
return cursor, await open_overlaps(connection, role, lane, pr, offset, limit)
|
|
460
|
+
|
|
461
|
+
async def list_triggers(self, lane: str | None) -> list[Trigger]:
|
|
462
|
+
async with self._engine.connect() as connection:
|
|
463
|
+
return await triggers_sql.list_triggers(connection, lane)
|
|
464
|
+
|
|
465
|
+
async def read_openrouter_budgets(self, now: datetime) -> list[tuple[str, float, str]]:
|
|
466
|
+
try:
|
|
467
|
+
async with self._engine.connect() as connection:
|
|
468
|
+
return await budgets_sql.read_openrouter_budgets(connection, now)
|
|
469
|
+
except DBAPIError as exc:
|
|
470
|
+
if retryable_search_write_error(exc) not in {"sqlite_busy", "sqlite_locked"}:
|
|
471
|
+
raise
|
|
472
|
+
raise OSError("OpenRouter budget targets temporarily unavailable") from None
|
|
473
|
+
|
|
474
|
+
async def read_budgets(self, run: str | None) -> list[Budget]:
|
|
475
|
+
async with self._engine.connect() as connection:
|
|
476
|
+
return await budgets_sql.read_budgets(connection, run)
|
|
477
|
+
|
|
478
|
+
async def read_merge_gate(self, repository: str | None, number: int) -> GateSnapshot:
|
|
479
|
+
async with self._engine.connect() as connection, connection.begin():
|
|
480
|
+
return await load_gate_snapshot(SqliteTransaction(connection), repository, number)
|
|
481
|
+
|
|
482
|
+
async def list_decisions(self, governs: str | None) -> list[Decision]:
|
|
483
|
+
async with self._engine.connect() as connection:
|
|
484
|
+
return await human_queue_sql.list_decisions(connection, governs)
|
|
485
|
+
|
|
486
|
+
async def pending_ask_issues(self, repository: str) -> set[int]:
|
|
487
|
+
async with self._engine.connect() as connection:
|
|
488
|
+
return await asks_sql.pending_ask_issues(connection, repository)
|
|
489
|
+
|
|
490
|
+
async def goals_use_blockers(self) -> bool:
|
|
491
|
+
async with self._engine.connect() as connection:
|
|
492
|
+
return await goals_sql.goals_use_blockers(connection)
|
|
493
|
+
|
|
494
|
+
async def read_goals(
|
|
495
|
+
self,
|
|
496
|
+
name: str | None,
|
|
497
|
+
repository: str | None,
|
|
498
|
+
human_login: str | None,
|
|
499
|
+
) -> tuple[list[StoredGoal], GoalFacts | None]:
|
|
500
|
+
async with self._engine.connect() as connection, connection.begin():
|
|
501
|
+
goals = await goals_sql.list_goals(connection, name)
|
|
502
|
+
if not goals or repository is None:
|
|
503
|
+
return goals, None
|
|
504
|
+
issues = await github_sql.github_resource(connection, repository, ISSUES, "")
|
|
505
|
+
if not verified_issue_projection(issues):
|
|
506
|
+
return goals, None
|
|
507
|
+
tree = (
|
|
508
|
+
await github_sql.github_resource(connection, repository, ISSUE_TREE, "")
|
|
509
|
+
if any(goal.uses_blockers for goal in goals)
|
|
510
|
+
else None
|
|
511
|
+
)
|
|
512
|
+
lanes = (
|
|
513
|
+
await board_lanes(connection, "orchestrator")
|
|
514
|
+
if any(goal.uses_lanes for goal in goals)
|
|
515
|
+
else []
|
|
516
|
+
)
|
|
517
|
+
decisions = (
|
|
518
|
+
await human_queue_sql.decision_refs(connection)
|
|
519
|
+
if any(goal.uses_decisions for goal in goals)
|
|
520
|
+
else []
|
|
521
|
+
)
|
|
522
|
+
return goals, project_goal_facts(
|
|
523
|
+
repository,
|
|
524
|
+
human_login,
|
|
525
|
+
issues,
|
|
526
|
+
tree,
|
|
527
|
+
lanes,
|
|
528
|
+
decisions,
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
async def list_asks(self, stale_only: bool) -> list[Ask]:
|
|
532
|
+
async with self._engine.connect() as connection:
|
|
533
|
+
return await asks_sql.list_asks(connection, stale_only)
|
|
534
|
+
|
|
535
|
+
async def pull_request(self, repository: str, number: int) -> PullRequest | None:
|
|
536
|
+
async with self._engine.connect() as connection:
|
|
537
|
+
return await github_sql.pull_request(connection, repository, number)
|
|
538
|
+
|
|
539
|
+
async def github_resource(
|
|
540
|
+
self, repository: str, resource: str, scope: str = ""
|
|
541
|
+
) -> GitHubResource | None:
|
|
542
|
+
async with self._engine.connect() as connection:
|
|
543
|
+
return await github_sql.github_resource(connection, repository, resource, scope)
|
|
544
|
+
|
|
545
|
+
async def github_pull_targets(self, repository: str) -> tuple[PullRequest, ...]:
|
|
546
|
+
async with self._engine.connect() as connection:
|
|
547
|
+
return await github_sql.github_pull_targets(connection, repository)
|
|
548
|
+
|
|
549
|
+
async def github_pending_merge_shas(
|
|
550
|
+
self, repository: str, as_of: str, limit: int
|
|
551
|
+
) -> tuple[PullRequest, ...]:
|
|
552
|
+
async with self._engine.connect() as connection:
|
|
553
|
+
return await github_sql.github_pending_merge_shas(connection, repository, as_of, limit)
|
|
554
|
+
|
|
555
|
+
async def fetch_cursor(self, repository: str, resource: str) -> FetchCursor | None:
|
|
556
|
+
async with self._engine.connect() as connection:
|
|
557
|
+
return await github_sql.fetch_cursor(connection, repository, resource)
|
|
558
|
+
|
|
559
|
+
async def fetch_retry(self, repository: str, resource: str) -> FetchRetry | None:
|
|
560
|
+
async with self._engine.connect() as connection:
|
|
561
|
+
return await github_sql.fetch_retry(connection, repository, resource)
|
|
562
|
+
|
|
563
|
+
async def read_next(self, role: str, offset: int, limit: int) -> tuple[int, list[Item]]:
|
|
564
|
+
async with self._engine.connect() as connection:
|
|
565
|
+
cursor = int((await connection.execute(HEAD_SEQ)).scalar_one())
|
|
566
|
+
return cursor, await open_items(connection, role, offset=offset, limit=limit)
|
|
567
|
+
|
|
568
|
+
async def read_open_item(self, role: str, item_id: str) -> Item | None:
|
|
569
|
+
async with self._engine.connect() as connection:
|
|
570
|
+
return await open_item(connection, role, item_id)
|
|
571
|
+
|
|
572
|
+
async def first_item_change(self, role: str, cursor: int) -> tuple[int, dict[str, Any] | None]:
|
|
573
|
+
async with self._engine.connect() as connection:
|
|
574
|
+
head = int((await connection.execute(HEAD_SEQ)).scalar_one())
|
|
575
|
+
return head, await first_change(connection, role, cursor)
|
|
576
|
+
|
|
577
|
+
async def ready_work_items(self) -> tuple[WorkItem, ...]:
|
|
578
|
+
async with self._engine.connect() as connection:
|
|
579
|
+
return await ready_work_items(connection)
|
|
580
|
+
|
|
581
|
+
async def pending_action(self) -> Action | None:
|
|
582
|
+
page = await self.pending_actions(after=0, limit=1)
|
|
583
|
+
return page[0].action if page else None
|
|
584
|
+
|
|
585
|
+
async def pending_actions(
|
|
586
|
+
self,
|
|
587
|
+
*,
|
|
588
|
+
after: int,
|
|
589
|
+
limit: int,
|
|
590
|
+
skip_branch_updates: bool = False,
|
|
591
|
+
skip_controller_merges: bool = False,
|
|
592
|
+
skip_bridge_workers: tuple[str, ...] | None = None,
|
|
593
|
+
) -> tuple[QueuedAction, ...]:
|
|
594
|
+
async with self._engine.connect() as connection:
|
|
595
|
+
return await pending_actions(
|
|
596
|
+
connection,
|
|
597
|
+
after=after,
|
|
598
|
+
limit=limit,
|
|
599
|
+
skip_branch_updates=skip_branch_updates,
|
|
600
|
+
skip_controller_merges=skip_controller_merges,
|
|
601
|
+
skip_bridge_workers=skip_bridge_workers,
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
async def bridge_readiness(self, workers: tuple[str, ...], now: str) -> OutboxReadiness:
|
|
605
|
+
async with self._engine.begin() as connection:
|
|
606
|
+
head = (await connection.execute(HEAD_SEQ)).scalar_one()
|
|
607
|
+
available = await bridge_action(connection, workers, now, None)
|
|
608
|
+
expires = await bridge_expiry(connection, workers, now)
|
|
609
|
+
return OutboxReadiness(head, head if available is not None else None, expires)
|
|
610
|
+
|
|
611
|
+
async def outbox_readiness(self, now: str) -> OutboxReadiness:
|
|
612
|
+
async with self._engine.connect() as connection:
|
|
613
|
+
head = int((await connection.execute(HEAD_SEQ)).scalar_one())
|
|
614
|
+
return await outbox_sql.readiness(connection, head, now)
|
|
615
|
+
|
|
616
|
+
async def close(self) -> None:
|
|
617
|
+
async with self._backup_lock:
|
|
618
|
+
writer, self._writer = self._writer, None
|
|
619
|
+
try:
|
|
620
|
+
if writer is not None:
|
|
621
|
+
await writer.close()
|
|
622
|
+
finally:
|
|
623
|
+
await self._engine.dispose()
|