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,102 @@
|
|
|
1
|
+
"""SQLite budget projection and committed reads."""
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from contextlib import closing
|
|
6
|
+
from dataclasses import asdict
|
|
7
|
+
from datetime import datetime, timedelta
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from sqlalchemy import text
|
|
11
|
+
from sqlalchemy.ext.asyncio import AsyncConnection
|
|
12
|
+
|
|
13
|
+
from plotroom.core.budgets import Budget
|
|
14
|
+
from plotroom.core.events import format_time
|
|
15
|
+
|
|
16
|
+
_BUDGET = text("SELECT * FROM budgets WHERE run = :run")
|
|
17
|
+
_BUDGETS = text("SELECT * FROM budgets ORDER BY run")
|
|
18
|
+
_INSERT = text("""
|
|
19
|
+
INSERT INTO budgets (id, run, lane, cap_usd, provider, key_scope, spent_usd, as_of)
|
|
20
|
+
VALUES (:id, :run, :lane, :cap_usd, :provider, :key_scope, :spent_usd, :as_of)
|
|
21
|
+
""")
|
|
22
|
+
_OPENROUTER_PREFIX = "openrouter.binding."
|
|
23
|
+
_OPENROUTER_RESERVE = text("""
|
|
24
|
+
INSERT INTO project_meta (key, value) VALUES (:key, :run)
|
|
25
|
+
ON CONFLICT (key) DO NOTHING RETURNING key
|
|
26
|
+
""")
|
|
27
|
+
_OPENROUTER_BUDGETS = text("""
|
|
28
|
+
SELECT budgets.run, budgets.cap_usd, substr(project_meta.key, :start) AS reservation
|
|
29
|
+
FROM budgets JOIN project_meta ON project_meta.value = budgets.run
|
|
30
|
+
JOIN lanes ON lanes.id = budgets.lane
|
|
31
|
+
WHERE budgets.provider = 'openrouter' AND project_meta.key GLOB :pattern
|
|
32
|
+
AND (lanes.state != 'archived' OR budgets.lane IN (
|
|
33
|
+
SELECT json_extract(fields, '$.args.lane') FROM events
|
|
34
|
+
WHERE kind = 'core.lane_archive' AND observed_at > :archive_cutoff
|
|
35
|
+
))
|
|
36
|
+
ORDER BY budgets.run
|
|
37
|
+
""")
|
|
38
|
+
_UPDATE_SPEND = text("UPDATE budgets SET spent_usd = :spent_usd, as_of = :as_of WHERE id = :id")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def foreign_openrouter_bindings(data_dir: Path, owners: Mapping[str, str]) -> set[str]:
|
|
42
|
+
"""Check earlier reservations even in inactive projects, without opening them for writes."""
|
|
43
|
+
blocked: set[str] = set()
|
|
44
|
+
for path in data_dir.glob("*.db"):
|
|
45
|
+
if all(project_id == path.stem for project_id in owners.values()):
|
|
46
|
+
continue
|
|
47
|
+
with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True, timeout=1)) as conn:
|
|
48
|
+
if conn.execute("SELECT 1 FROM sqlite_schema LIMIT 1").fetchone() is None:
|
|
49
|
+
continue
|
|
50
|
+
rows = conn.execute(
|
|
51
|
+
"SELECT key FROM project_meta WHERE key GLOB ?", (_OPENROUTER_PREFIX + "*",)
|
|
52
|
+
)
|
|
53
|
+
for (key,) in rows:
|
|
54
|
+
reservation = str(key).removeprefix(_OPENROUTER_PREFIX)
|
|
55
|
+
owner = owners.get(reservation)
|
|
56
|
+
if owner is not None and owner != path.stem:
|
|
57
|
+
blocked.add(reservation)
|
|
58
|
+
return blocked
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def reserve_openrouter_key(connection: AsyncConnection, reservation: str, run: str) -> bool:
|
|
62
|
+
inserted = await connection.execute(
|
|
63
|
+
_OPENROUTER_RESERVE, {"key": _OPENROUTER_PREFIX + reservation, "run": run}
|
|
64
|
+
)
|
|
65
|
+
return inserted.scalar_one_or_none() is not None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def read_openrouter_budgets(
|
|
69
|
+
connection: AsyncConnection, now: datetime
|
|
70
|
+
) -> list[tuple[str, float, str]]:
|
|
71
|
+
rows = await connection.execute(
|
|
72
|
+
_OPENROUTER_BUDGETS,
|
|
73
|
+
{
|
|
74
|
+
"start": len(_OPENROUTER_PREFIX) + 1,
|
|
75
|
+
"pattern": _OPENROUTER_PREFIX + "*",
|
|
76
|
+
"archive_cutoff": format_time(now - timedelta(minutes=2)),
|
|
77
|
+
},
|
|
78
|
+
)
|
|
79
|
+
return [(str(row.run), float(row.cap_usd), str(row.reservation)) for row in rows]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
async def find_budget(connection: AsyncConnection, run: str) -> Budget | None:
|
|
83
|
+
row = (await connection.execute(_BUDGET, {"run": run})).mappings().one_or_none()
|
|
84
|
+
return Budget(**row) if row is not None else None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def read_budgets(connection: AsyncConnection, run: str | None) -> list[Budget]:
|
|
88
|
+
if run is None:
|
|
89
|
+
return [Budget(**row) for row in (await connection.execute(_BUDGETS)).mappings()]
|
|
90
|
+
budget = await find_budget(connection, run)
|
|
91
|
+
return [] if budget is None else [budget]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def insert_budget(connection: AsyncConnection, budget: Budget) -> None:
|
|
95
|
+
await connection.execute(_INSERT, asdict(budget))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def update_budget_spend(connection: AsyncConnection, budget: Budget) -> None:
|
|
99
|
+
await connection.execute(
|
|
100
|
+
_UPDATE_SPEND,
|
|
101
|
+
{"id": budget.id, "spent_usd": budget.spent_usd, "as_of": budget.as_of},
|
|
102
|
+
)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""SQLite persistence for a lane's checklist header and ordered steps."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import text
|
|
6
|
+
from sqlalchemy.ext.asyncio import AsyncConnection
|
|
7
|
+
|
|
8
|
+
from plotroom.core.checklists import Checklist, ChecklistStep
|
|
9
|
+
|
|
10
|
+
_HEADER = text("SELECT * FROM lane_checklists WHERE lane = :lane")
|
|
11
|
+
_STEPS = text("""
|
|
12
|
+
SELECT step, owner, ref, completion_ref
|
|
13
|
+
FROM lane_checklist_steps WHERE lane = :lane ORDER BY position
|
|
14
|
+
""")
|
|
15
|
+
_SAVE = text("""
|
|
16
|
+
INSERT INTO lane_checklists (lane, version, repository, branch, pr, head_sha, state)
|
|
17
|
+
VALUES (:lane, :version, :repository, :branch, :pr, :head_sha, :state)
|
|
18
|
+
ON CONFLICT (lane) DO UPDATE SET version = excluded.version,
|
|
19
|
+
repository = excluded.repository, branch = excluded.branch, pr = excluded.pr,
|
|
20
|
+
head_sha = excluded.head_sha, state = excluded.state
|
|
21
|
+
""")
|
|
22
|
+
_CLEAR_STEPS = text("DELETE FROM lane_checklist_steps WHERE lane = :lane")
|
|
23
|
+
_INSERT_STEP = text("""
|
|
24
|
+
INSERT INTO lane_checklist_steps (lane, position, step, owner, ref, completion_ref)
|
|
25
|
+
VALUES (:lane, :position, :step, :owner, :ref, :completion_ref)
|
|
26
|
+
""")
|
|
27
|
+
_COMPLETE_STEP = text("""
|
|
28
|
+
UPDATE lane_checklist_steps SET completion_ref = :completion_ref
|
|
29
|
+
WHERE lane = :lane AND step = :step AND completion_ref IS NULL
|
|
30
|
+
AND EXISTS (
|
|
31
|
+
SELECT 1 FROM lane_checklists
|
|
32
|
+
WHERE lane = :lane AND version = :version AND state = 'active'
|
|
33
|
+
)
|
|
34
|
+
RETURNING step
|
|
35
|
+
""")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def find_checklist(connection: AsyncConnection, lane: str) -> Checklist | None:
|
|
39
|
+
keys = {"lane": lane}
|
|
40
|
+
header = (await connection.execute(_HEADER, keys)).mappings().first()
|
|
41
|
+
if header is None:
|
|
42
|
+
return None
|
|
43
|
+
rows = (await connection.execute(_STEPS, keys)).mappings()
|
|
44
|
+
steps = tuple(ChecklistStep(**row) for row in rows)
|
|
45
|
+
return Checklist(**header, steps=steps)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def save_checklist(connection: AsyncConnection, checklist: Checklist) -> None:
|
|
49
|
+
keys = {
|
|
50
|
+
"lane": checklist.lane,
|
|
51
|
+
"version": checklist.version,
|
|
52
|
+
"repository": checklist.repository,
|
|
53
|
+
"branch": checklist.branch,
|
|
54
|
+
"pr": checklist.pr,
|
|
55
|
+
"head_sha": checklist.head_sha,
|
|
56
|
+
"state": checklist.state,
|
|
57
|
+
}
|
|
58
|
+
await connection.execute(_SAVE, keys)
|
|
59
|
+
await connection.execute(_CLEAR_STEPS, {"lane": checklist.lane})
|
|
60
|
+
if checklist.steps:
|
|
61
|
+
await connection.execute(
|
|
62
|
+
_INSERT_STEP,
|
|
63
|
+
[
|
|
64
|
+
{"lane": checklist.lane, "position": position, **asdict(step)}
|
|
65
|
+
for position, step in enumerate(checklist.steps)
|
|
66
|
+
],
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def set_checklist_step_completion(
|
|
71
|
+
connection: AsyncConnection, lane: str, version: int, step: str, completion_ref: str
|
|
72
|
+
) -> bool:
|
|
73
|
+
result = await connection.execute(
|
|
74
|
+
_COMPLETE_STEP,
|
|
75
|
+
{"lane": lane, "version": version, "step": step, "completion_ref": completion_ref},
|
|
76
|
+
)
|
|
77
|
+
return result.scalar_one_or_none() is not None
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Reads and writes of path claims in the project database."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import text
|
|
6
|
+
from sqlalchemy.ext.asyncio import AsyncConnection
|
|
7
|
+
|
|
8
|
+
from plotroom.core.claims import Claim
|
|
9
|
+
|
|
10
|
+
_LANE_SCOPE = "(:lane IS NULL OR lane_claims.lane = :lane)"
|
|
11
|
+
_VISIBLE = (
|
|
12
|
+
"FROM lane_claims JOIN lanes ON lanes.id = lane_claims.lane "
|
|
13
|
+
"WHERE lanes.state != 'archived' "
|
|
14
|
+
"AND (:role IN ('orchestrator', 'clerk') OR :role = 'worker:' || lanes.worker)"
|
|
15
|
+
)
|
|
16
|
+
_READ = text(
|
|
17
|
+
f"SELECT lane_claims.* {_VISIBLE} AND {_LANE_SCOPE} "
|
|
18
|
+
"ORDER BY lane, glob LIMIT :limit OFFSET :offset"
|
|
19
|
+
)
|
|
20
|
+
_COUNT = text(f"SELECT count(*) {_VISIBLE}")
|
|
21
|
+
_SAVE = text(
|
|
22
|
+
"INSERT INTO lane_claims (lane, glob, reason) VALUES (:lane, :glob, :reason) "
|
|
23
|
+
"ON CONFLICT(lane, glob) DO UPDATE SET reason=excluded.reason"
|
|
24
|
+
)
|
|
25
|
+
_DELETE = text("DELETE FROM lane_claims WHERE lane = :lane AND glob = :glob")
|
|
26
|
+
_DELETE_LANE = text("DELETE FROM lane_claims WHERE lane = :lane")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def read_claims(
|
|
30
|
+
connection: AsyncConnection,
|
|
31
|
+
role: str,
|
|
32
|
+
lane: str | None = None,
|
|
33
|
+
offset: int = 0,
|
|
34
|
+
limit: int = -1,
|
|
35
|
+
) -> list[Claim]:
|
|
36
|
+
rows = await connection.execute(
|
|
37
|
+
_READ, {"role": role, "lane": lane, "offset": offset, "limit": limit}
|
|
38
|
+
)
|
|
39
|
+
return [Claim(row.lane, row.glob, row.reason) for row in rows]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def count_claims(connection: AsyncConnection, role: str) -> int:
|
|
43
|
+
return int((await connection.execute(_COUNT, {"role": role})).scalar_one())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def save_claims(connection: AsyncConnection, claims: list[Claim]) -> None:
|
|
47
|
+
await connection.execute(_SAVE, [asdict(entry) for entry in claims])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def delete_claims(connection: AsyncConnection, lane: str, globs: list[str] | None) -> None:
|
|
51
|
+
if globs is None:
|
|
52
|
+
await connection.execute(_DELETE_LANE, {"lane": lane})
|
|
53
|
+
elif globs:
|
|
54
|
+
await connection.execute(_DELETE, [{"lane": lane, "glob": glob} for glob in globs])
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Cursor and vector revisions for one model in the project's SQLite file."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
|
|
7
|
+
from sqlalchemy import bindparam, text
|
|
8
|
+
from sqlalchemy.ext.asyncio import AsyncConnection
|
|
9
|
+
|
|
10
|
+
from plotroom.adapters.store_sqlite.search_sql import literal_phrase, search_records
|
|
11
|
+
from plotroom.core.search_sources import EVENT_KINDS
|
|
12
|
+
from plotroom.ports.search import (
|
|
13
|
+
ASK_KIND,
|
|
14
|
+
DECISION_KIND,
|
|
15
|
+
ISSUE_COMMENT_KIND,
|
|
16
|
+
PR_BODY_KIND,
|
|
17
|
+
BackfillSource,
|
|
18
|
+
EmbeddedRecord,
|
|
19
|
+
EmbeddingModel,
|
|
20
|
+
EmbeddingPending,
|
|
21
|
+
EmbeddingReadiness,
|
|
22
|
+
EmbeddingRevision,
|
|
23
|
+
IndexedEmbedding,
|
|
24
|
+
SearchHit,
|
|
25
|
+
SearchPage,
|
|
26
|
+
SearchRecord,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
EXCERPT_LIMIT = 240
|
|
30
|
+
SOURCE_KINDS = {
|
|
31
|
+
BackfillSource.EVENTS: EVENT_KINDS,
|
|
32
|
+
BackfillSource.DECISIONS: {DECISION_KIND},
|
|
33
|
+
BackfillSource.ASKS: {ASK_KIND},
|
|
34
|
+
BackfillSource.COMMENTS: {ISSUE_COMMENT_KIND},
|
|
35
|
+
BackfillSource.PULLS: {PR_BODY_KIND},
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
READ_CURSOR = text("""
|
|
39
|
+
SELECT index_seq FROM embedding_cursors WHERE model = :model AND dimension = :dimension
|
|
40
|
+
""")
|
|
41
|
+
READ_PAGE = text("""
|
|
42
|
+
SELECT r.seq, r.kind, r.record_id,
|
|
43
|
+
CASE WHEN r.embeddable AND v.record_seq IS NULL AND x.record_seq IS NULL
|
|
44
|
+
THEN r.body END AS body
|
|
45
|
+
FROM search_records AS r
|
|
46
|
+
LEFT JOIN search_vectors AS v
|
|
47
|
+
ON v.record_seq = r.seq AND v.model = :model AND v.dimension = :dimension
|
|
48
|
+
LEFT JOIN embedding_rejections AS x
|
|
49
|
+
ON x.record_seq = r.seq AND x.model = :model AND x.dimension = :dimension
|
|
50
|
+
WHERE r.seq > :after
|
|
51
|
+
ORDER BY r.seq LIMIT :limit
|
|
52
|
+
""")
|
|
53
|
+
HIGH_WATER = text("SELECT seq FROM sqlite_sequence WHERE name = 'search_records'")
|
|
54
|
+
BATCH_REVISIONS = text("""
|
|
55
|
+
SELECT seq, kind, record_id, embeddable FROM search_records
|
|
56
|
+
WHERE seq IN :sequences OR (kind, record_id) IN (
|
|
57
|
+
SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]')
|
|
58
|
+
FROM json_each(:identities)
|
|
59
|
+
)
|
|
60
|
+
""").bindparams(bindparam("sequences", expanding=True))
|
|
61
|
+
SAVE_CURSOR = text("""
|
|
62
|
+
INSERT INTO embedding_cursors (model, dimension, index_seq)
|
|
63
|
+
VALUES (:model, :dimension, :seq)
|
|
64
|
+
ON CONFLICT (model, dimension) DO UPDATE SET index_seq = excluded.index_seq
|
|
65
|
+
""")
|
|
66
|
+
SAVE_VECTOR = text("""
|
|
67
|
+
INSERT INTO search_vectors (model, dimension, record_seq, vector)
|
|
68
|
+
VALUES (:model, :dimension, :seq, :vector)
|
|
69
|
+
""")
|
|
70
|
+
SAVE_REJECTION = text("""
|
|
71
|
+
INSERT INTO embedding_rejections (model, dimension, record_seq, reason)
|
|
72
|
+
VALUES (:model, :dimension, :seq, :reason)
|
|
73
|
+
""")
|
|
74
|
+
REJECTED_MATCH = text("""
|
|
75
|
+
SELECT EXISTS (
|
|
76
|
+
SELECT 1 FROM message_fts
|
|
77
|
+
JOIN embedding_rejections AS x ON x.record_seq = message_fts.rowid
|
|
78
|
+
JOIN search_records AS r ON r.seq = x.record_seq
|
|
79
|
+
WHERE message_fts MATCH :phrase AND x.model = :model AND x.dimension = :dimension
|
|
80
|
+
AND (:kinds IS NULL OR r.kind IN (SELECT value FROM json_each(:kinds)))
|
|
81
|
+
)
|
|
82
|
+
""")
|
|
83
|
+
UNFINISHED_SOURCES = text("""
|
|
84
|
+
SELECT EXISTS (
|
|
85
|
+
SELECT 1 FROM json_each(:sources) AS sources
|
|
86
|
+
LEFT JOIN project_meta AS meta ON meta.key = 'search.backfill.' || sources.value
|
|
87
|
+
WHERE meta.value IS NOT 'null'
|
|
88
|
+
)
|
|
89
|
+
""")
|
|
90
|
+
PENDING_REVISIONS = text("""
|
|
91
|
+
SELECT EXISTS (
|
|
92
|
+
SELECT 1 FROM search_records AS r
|
|
93
|
+
WHERE r.embeddable AND r.kind IN (SELECT value FROM json_each(:kinds))
|
|
94
|
+
AND r.seq > COALESCE((
|
|
95
|
+
SELECT index_seq FROM embedding_cursors
|
|
96
|
+
WHERE model = :model AND dimension = :dimension
|
|
97
|
+
), 0)
|
|
98
|
+
AND NOT EXISTS (
|
|
99
|
+
SELECT 1 FROM search_vectors AS v
|
|
100
|
+
WHERE v.model = :model AND v.dimension = :dimension AND v.record_seq = r.seq
|
|
101
|
+
)
|
|
102
|
+
AND NOT EXISTS (
|
|
103
|
+
SELECT 1 FROM embedding_rejections AS x
|
|
104
|
+
WHERE x.model = :model AND x.dimension = :dimension AND x.record_seq = r.seq
|
|
105
|
+
)
|
|
106
|
+
)
|
|
107
|
+
""")
|
|
108
|
+
ELIGIBLE_RECORDS = text("""
|
|
109
|
+
SELECT EXISTS (
|
|
110
|
+
SELECT 1 FROM search_records AS r
|
|
111
|
+
WHERE r.embeddable AND r.kind IN (SELECT value FROM json_each(:kinds))
|
|
112
|
+
AND NOT EXISTS (
|
|
113
|
+
SELECT 1 FROM embedding_rejections AS x
|
|
114
|
+
WHERE x.model = :model AND x.dimension = :dimension AND x.record_seq = r.seq
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
""")
|
|
118
|
+
COUNT_RECORDS = text("""
|
|
119
|
+
SELECT count(*) FILTER (WHERE x.record_seq IS NULL) AS eligible,
|
|
120
|
+
count(v.record_seq) AS indexed
|
|
121
|
+
FROM search_records AS r
|
|
122
|
+
LEFT JOIN search_vectors AS v
|
|
123
|
+
ON v.record_seq = r.seq AND v.model = :model AND v.dimension = :dimension
|
|
124
|
+
LEFT JOIN embedding_rejections AS x
|
|
125
|
+
ON x.record_seq = r.seq AND x.model = :model AND x.dimension = :dimension
|
|
126
|
+
WHERE r.embeddable
|
|
127
|
+
AND (:kinds IS NULL OR r.kind IN (SELECT value FROM json_each(:kinds)))
|
|
128
|
+
""")
|
|
129
|
+
FIND_VECTORS = text("""
|
|
130
|
+
SELECT r.record_id AS id, r.kind, substr(CAST(r.body AS BLOB), 1, :excerpt_bytes) AS excerpt
|
|
131
|
+
FROM search_vectors AS v JOIN search_records AS r ON v.record_seq = r.seq
|
|
132
|
+
WHERE v.model = :model AND v.dimension = :dimension AND r.embeddable
|
|
133
|
+
AND (:kinds IS NULL OR r.kind IN (SELECT value FROM json_each(:kinds)))
|
|
134
|
+
ORDER BY vec_distance_l2(v.vector, :query), r.seq DESC
|
|
135
|
+
LIMIT :limit
|
|
136
|
+
""")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def read_cursor(connection: AsyncConnection, model: EmbeddingModel) -> int:
|
|
140
|
+
row = await connection.execute(READ_CURSOR, {"model": model.name, "dimension": model.dimension})
|
|
141
|
+
return int(row.scalar_one_or_none() or 0)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
async def read_page(
|
|
145
|
+
connection: AsyncConnection, model: EmbeddingModel, after: int, limit: int
|
|
146
|
+
) -> list[EmbeddingRevision]:
|
|
147
|
+
key = {"model": model.name, "dimension": model.dimension}
|
|
148
|
+
rows = await connection.execute(READ_PAGE, {**key, "after": after, "limit": limit})
|
|
149
|
+
return [
|
|
150
|
+
EmbeddingRevision(
|
|
151
|
+
row.seq,
|
|
152
|
+
SearchRecord(row.kind, row.record_id, row.body) if row.body is not None else None,
|
|
153
|
+
)
|
|
154
|
+
for row in rows
|
|
155
|
+
]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
async def commit_batch(
|
|
159
|
+
connection: AsyncConnection,
|
|
160
|
+
model: EmbeddingModel,
|
|
161
|
+
expected: int,
|
|
162
|
+
through: int,
|
|
163
|
+
records: tuple[IndexedEmbedding, ...],
|
|
164
|
+
) -> bool:
|
|
165
|
+
# BEGIN IMMEDIATE serializes cursor validation, revision checks and writes.
|
|
166
|
+
if await read_cursor(connection, model) != expected:
|
|
167
|
+
return False
|
|
168
|
+
if through <= expected:
|
|
169
|
+
raise ValueError("embedding batch must advance the cursor")
|
|
170
|
+
high_water = (await connection.execute(HIGH_WATER)).scalar_one_or_none()
|
|
171
|
+
if high_water is None or through > high_water:
|
|
172
|
+
raise ValueError("embedding batch must end within committed search revisions")
|
|
173
|
+
key = {"model": model.name, "dimension": model.dimension}
|
|
174
|
+
if records:
|
|
175
|
+
sequences = {record.seq for record in records}
|
|
176
|
+
if len(sequences) != len(records) or not all(
|
|
177
|
+
expected < seq <= through for seq in sequences
|
|
178
|
+
):
|
|
179
|
+
raise ValueError("embedding records must be revisions within the batch interval")
|
|
180
|
+
identities = {(record.kind, record.id) for record in records}
|
|
181
|
+
result = await connection.execute(
|
|
182
|
+
BATCH_REVISIONS,
|
|
183
|
+
{"sequences": tuple(sequences), "identities": json.dumps(list(identities))},
|
|
184
|
+
)
|
|
185
|
+
rows = result.all()
|
|
186
|
+
by_seq = {row.seq: row for row in rows}
|
|
187
|
+
by_identity = {(row.kind, row.record_id): row for row in rows}
|
|
188
|
+
vectors: list[dict[str, str | int | bytes]] = []
|
|
189
|
+
rejections: list[dict[str, str | int]] = []
|
|
190
|
+
for record in records:
|
|
191
|
+
current = by_identity.get((record.kind, record.id))
|
|
192
|
+
if current is not None and current.seq == record.seq and current.embeddable:
|
|
193
|
+
if isinstance(record, EmbeddedRecord):
|
|
194
|
+
vectors.append({**key, "seq": record.seq, "vector": record.vector})
|
|
195
|
+
else:
|
|
196
|
+
rejections.append({**key, "seq": record.seq, "reason": record.reason})
|
|
197
|
+
elif current is None or current.seq <= through or record.seq in by_seq:
|
|
198
|
+
raise ValueError("embedding records must be revisions within the batch interval")
|
|
199
|
+
# Skip dispositions for revisions superseded during the HTTP request.
|
|
200
|
+
if vectors:
|
|
201
|
+
await connection.execute(SAVE_VECTOR, vectors)
|
|
202
|
+
if rejections:
|
|
203
|
+
await connection.execute(SAVE_REJECTION, rejections)
|
|
204
|
+
await connection.execute(SAVE_CURSOR, {**key, "seq": through})
|
|
205
|
+
return True
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
async def backfill_pending(connection: AsyncConnection, kinds: tuple[str, ...]) -> bool:
|
|
209
|
+
sources = [source for source, members in SOURCE_KINDS.items() if members.intersection(kinds)]
|
|
210
|
+
pending = await connection.execute(UNFINISHED_SOURCES, {"sources": json.dumps(sources)})
|
|
211
|
+
return bool(pending.scalar_one())
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
async def preflight(
|
|
215
|
+
connection: AsyncConnection,
|
|
216
|
+
model: EmbeddingModel,
|
|
217
|
+
kinds: tuple[str, ...],
|
|
218
|
+
query_text: str | None,
|
|
219
|
+
) -> EmbeddingReadiness:
|
|
220
|
+
if not kinds:
|
|
221
|
+
return EmbeddingReadiness.EMPTY
|
|
222
|
+
params = {"model": model.name, "dimension": model.dimension, "kinds": json.dumps(kinds)}
|
|
223
|
+
if await rejected_match(connection, params, query_text):
|
|
224
|
+
return EmbeddingReadiness.REJECTED_MATCH
|
|
225
|
+
if await backfill_pending(connection, kinds):
|
|
226
|
+
return EmbeddingReadiness.PENDING
|
|
227
|
+
# The writer advances the cursor and saves dispositions atomically. Migrated vectors
|
|
228
|
+
# can already cover newer revisions, so only unresolved revisions above it are pending.
|
|
229
|
+
if (await connection.execute(PENDING_REVISIONS, params)).scalar_one():
|
|
230
|
+
return EmbeddingReadiness.PENDING
|
|
231
|
+
if (await connection.execute(ELIGIBLE_RECORDS, params)).scalar_one():
|
|
232
|
+
return EmbeddingReadiness.READY
|
|
233
|
+
return EmbeddingReadiness.EMPTY
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
async def rejected_match(
|
|
237
|
+
connection: AsyncConnection, key: Mapping[str, str | int | None], query_text: str | None
|
|
238
|
+
) -> bool:
|
|
239
|
+
if query_text is None:
|
|
240
|
+
return False
|
|
241
|
+
result = await connection.execute(REJECTED_MATCH, {**key, "phrase": literal_phrase(query_text)})
|
|
242
|
+
return bool(result.scalar_one())
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
async def query_vectors(
|
|
246
|
+
connection: AsyncConnection,
|
|
247
|
+
model: EmbeddingModel,
|
|
248
|
+
query: bytes,
|
|
249
|
+
limit: int,
|
|
250
|
+
kinds: tuple[str, ...] | None,
|
|
251
|
+
query_text: str | None,
|
|
252
|
+
) -> SearchPage:
|
|
253
|
+
key = {
|
|
254
|
+
"model": model.name,
|
|
255
|
+
"dimension": model.dimension,
|
|
256
|
+
"kinds": None if kinds is None else json.dumps(kinds),
|
|
257
|
+
}
|
|
258
|
+
if query_text is not None and await rejected_match(connection, key, query_text):
|
|
259
|
+
page = await search_records(connection, query_text, kinds, limit)
|
|
260
|
+
return replace(page, mode="lexical", fallback_reason="embedding_rejected")
|
|
261
|
+
if kinds is not None and await backfill_pending(connection, kinds):
|
|
262
|
+
raise EmbeddingPending
|
|
263
|
+
eligible, indexed = (await connection.execute(COUNT_RECORDS, key)).one()
|
|
264
|
+
# Direct index reads can inspect an incomplete prefix.
|
|
265
|
+
if kinds is not None and eligible != indexed:
|
|
266
|
+
raise EmbeddingPending
|
|
267
|
+
# A BLOB slice retains embedded NULs and bounds the read to four bytes per character.
|
|
268
|
+
rows = await connection.execute(
|
|
269
|
+
FIND_VECTORS, {**key, "query": query, "limit": limit, "excerpt_bytes": 4 * EXCERPT_LIMIT}
|
|
270
|
+
)
|
|
271
|
+
hits = tuple(
|
|
272
|
+
SearchHit(row.id, row.kind, row.excerpt.decode("utf-8", "ignore")[:EXCERPT_LIMIT])
|
|
273
|
+
for row in rows
|
|
274
|
+
)
|
|
275
|
+
return SearchPage(hits, indexed)
|