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
plotroom/core/roles.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Roles (AD-8): who an input comes from. ``<role>:<request_id>`` is unambiguous because no role
|
|
2
|
+
contains more than one colon and a worker slug contains none."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from plotroom.core.events import Event
|
|
13
|
+
from plotroom.core.lanes import Lane
|
|
14
|
+
from plotroom.core.next_items import Item
|
|
15
|
+
|
|
16
|
+
SIMPLE_TOKEN_ROLES = frozenset({"orchestrator", "clerk", "drain", "bridge"})
|
|
17
|
+
SIMPLE_ROLES = SIMPLE_TOKEN_ROLES | {"system"}
|
|
18
|
+
WORKER_FAMILY = "worker"
|
|
19
|
+
ROLE_FAMILIES = SIMPLE_ROLES | {WORKER_FAMILY}
|
|
20
|
+
_WORKER = re.compile(r"worker:([a-z0-9](?:[a-z0-9_-]*[a-z0-9])?)")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Identity:
|
|
25
|
+
project_id: str
|
|
26
|
+
role: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def role_family(role: str) -> str:
|
|
30
|
+
"""The role family a registry names: ``worker:<slug>`` is ``worker``, the rest are themselves.
|
|
31
|
+
|
|
32
|
+
Raises ``ValueError`` for anything outside the role grammar.
|
|
33
|
+
"""
|
|
34
|
+
if role in SIMPLE_ROLES:
|
|
35
|
+
return role
|
|
36
|
+
if _WORKER.fullmatch(role):
|
|
37
|
+
return WORKER_FAMILY
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"invalid role {role!r}: expected one of {sorted(SIMPLE_ROLES)} or worker:<slug>"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def validate_token_role(role: str) -> None:
|
|
44
|
+
"""Validate a role that can be issued a credential."""
|
|
45
|
+
if role_family(role) == "system":
|
|
46
|
+
raise ValueError("system is an internal role and cannot have a token")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class OwnershipView:
|
|
51
|
+
"""The calling role and read access to events in the command's transaction."""
|
|
52
|
+
|
|
53
|
+
role: str
|
|
54
|
+
_lookup: Callable[[str, str, str], Awaitable[Event | None]] = field(repr=False)
|
|
55
|
+
|
|
56
|
+
_item: Callable[[str], Awaitable[Item | None]] = field(repr=False)
|
|
57
|
+
|
|
58
|
+
_lane: Callable[[str], Awaitable[Lane | None]] = field(repr=False)
|
|
59
|
+
|
|
60
|
+
async def find_lane(self, lane_id: str) -> Lane | None:
|
|
61
|
+
return await self._lane(lane_id)
|
|
62
|
+
|
|
63
|
+
async def find_event(self, source: str, kind: str, upstream_id: str) -> Event | None:
|
|
64
|
+
return await self._lookup(source, kind, upstream_id)
|
|
65
|
+
|
|
66
|
+
async def find_item(self, item_id: str) -> Item | None:
|
|
67
|
+
return await self._item(item_id)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
type Ownership = Callable[[OwnershipView, dict[str, Any]], Awaitable[bool]]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class WriterRule:
|
|
75
|
+
"""A role family allowed to write, optionally subject to a read-only ownership predicate."""
|
|
76
|
+
|
|
77
|
+
family: str
|
|
78
|
+
owns: Ownership | None = None
|
|
79
|
+
|
|
80
|
+
def __post_init__(self) -> None:
|
|
81
|
+
if self.family not in ROLE_FAMILIES:
|
|
82
|
+
raise ValueError(f"unknown writer role family {self.family!r}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class WriterRules:
|
|
86
|
+
"""Authorization rows for command names and fully qualified event kinds."""
|
|
87
|
+
|
|
88
|
+
def __init__(self) -> None:
|
|
89
|
+
self._rules: dict[str, dict[str, WriterRule]] = {}
|
|
90
|
+
|
|
91
|
+
def declare(self, operation: str, rules: tuple[WriterRule, ...]) -> None:
|
|
92
|
+
if operation in self._rules:
|
|
93
|
+
raise ValueError(f"writer rules for {operation!r} are already declared")
|
|
94
|
+
by_family = {rule.family: rule for rule in rules}
|
|
95
|
+
if len(by_family) != len(rules):
|
|
96
|
+
raise ValueError(f"writer rules for {operation!r} declare a role family twice")
|
|
97
|
+
self._rules[operation] = by_family
|
|
98
|
+
|
|
99
|
+
def rule_for(self, operation: str, family: str) -> WriterRule | None:
|
|
100
|
+
return self._rules.get(operation, {}).get(family)
|
plotroom/core/routing.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Project-local assignment of hands-on action kinds to lanes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from plotroom.core.events import FieldSpec, LedgerError
|
|
9
|
+
from plotroom.core.next_items import ItemKind
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
13
|
+
|
|
14
|
+
ACTION_KIND = FieldSpec("action_kind", "str")
|
|
15
|
+
MISSING_ROUTE = ItemKind("route_missing", 20, True, ("Assign a lane to this action kind",))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def validate_route_label(value: object, field: str) -> str:
|
|
19
|
+
error = f"{field} must be a non-blank string of at most 128 UTF-8 bytes without NUL"
|
|
20
|
+
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
|
21
|
+
raise LedgerError("invalid", error)
|
|
22
|
+
try:
|
|
23
|
+
if len(value.encode()) > 128:
|
|
24
|
+
raise LedgerError("invalid", error)
|
|
25
|
+
except UnicodeEncodeError as exc:
|
|
26
|
+
raise LedgerError("invalid", error) from exc
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
async def seed_routes(uow: UnitOfWork, routes: Mapping[str, str]) -> None:
|
|
31
|
+
"""Import the configuration as a whole on the first startup with routes."""
|
|
32
|
+
if await uow.has_routes():
|
|
33
|
+
return
|
|
34
|
+
for action_kind, lane in routes.items():
|
|
35
|
+
await uow.save_route(action_kind, lane)
|
|
36
|
+
await uow.clear_item(MISSING_ROUTE.name, action_kind)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def route(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
|
|
40
|
+
action_kind = validate_route_label(args["action_kind"], "action_kind")
|
|
41
|
+
lane = validate_route_label(args["lane"], "lane")
|
|
42
|
+
await uow.save_route(action_kind, lane)
|
|
43
|
+
await uow.clear_item(MISSING_ROUTE.name, action_kind)
|
|
44
|
+
return {"action_kind": action_kind, "lane": lane}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def route_request(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
|
|
48
|
+
action_kind = validate_route_label(args["action_kind"], "action_kind")
|
|
49
|
+
lane = await uow.find_route(action_kind)
|
|
50
|
+
if lane is not None:
|
|
51
|
+
return {"action_kind": action_kind, "lane": lane}
|
|
52
|
+
item = await uow.raise_item(
|
|
53
|
+
MISSING_ROUTE.name, action_kind, "orchestrator", {"action_kind": action_kind}
|
|
54
|
+
)
|
|
55
|
+
return {"action_kind": action_kind, "lane": None, "item": item.id}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Worker-owned run observations."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
from plotroom.core.events import FieldSpec, LedgerError, NewEvent
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
10
|
+
|
|
11
|
+
RUN_STATUS = "run.status"
|
|
12
|
+
RUN_ID = FieldSpec("run_id", "str")
|
|
13
|
+
RUN_STATE = FieldSpec("state", "str")
|
|
14
|
+
RUN_FIELDS = (RUN_ID, RUN_STATE, FieldSpec("finished", "bool"))
|
|
15
|
+
FINISHED = frozenset({"completed", "succeeded", "failed", "canceled"})
|
|
16
|
+
STATES = FINISHED | {"queued", "running", "in_progress"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def validate_identity(value: str, name: str) -> None:
|
|
20
|
+
try:
|
|
21
|
+
size = len(value.encode("utf-8"))
|
|
22
|
+
except UnicodeError:
|
|
23
|
+
raise LedgerError("invalid", f"{name} must be valid UTF-8") from None
|
|
24
|
+
if not value.strip() or "\0" in value or size > 256:
|
|
25
|
+
raise LedgerError("invalid", f"{name} must be 1-256 UTF-8 bytes and contain no NUL")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
async def run_report(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
|
|
29
|
+
lane: str = args["lane"]
|
|
30
|
+
run_id: str = args["run_id"]
|
|
31
|
+
state: str = args["state"]
|
|
32
|
+
validate_identity(run_id, "run_id")
|
|
33
|
+
if state not in STATES:
|
|
34
|
+
raise LedgerError("invalid", f"run state must be one of {', '.join(sorted(STATES))}")
|
|
35
|
+
current = await uow.find_lane(lane)
|
|
36
|
+
if current is None or current.state == "archived":
|
|
37
|
+
raise LedgerError("conflict", "a run report requires a current lane")
|
|
38
|
+
previous = await uow.latest_run_report(run_id)
|
|
39
|
+
if previous is not None:
|
|
40
|
+
if previous.lane_id != lane:
|
|
41
|
+
raise LedgerError("conflict", "run_id already belongs to another lane")
|
|
42
|
+
if previous.fields["finished"] and state not in FINISHED:
|
|
43
|
+
raise LedgerError("conflict", "a finished run cannot return to a nonterminal state")
|
|
44
|
+
result = await uow.append(
|
|
45
|
+
NewEvent(
|
|
46
|
+
"run",
|
|
47
|
+
RUN_STATUS,
|
|
48
|
+
json.dumps([lane, run_id, state], separators=(",", ":")),
|
|
49
|
+
{"run_id": run_id, "state": state, "finished": state in FINISHED},
|
|
50
|
+
lane_id=lane,
|
|
51
|
+
)
|
|
52
|
+
)
|
|
53
|
+
return {"event_id": result.event.id}
|
plotroom/core/search.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Backfill, embed and query committed search records."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import math
|
|
8
|
+
import struct
|
|
9
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
10
|
+
from dataclasses import dataclass, replace
|
|
11
|
+
from functools import partial
|
|
12
|
+
from typing import TYPE_CHECKING, Protocol
|
|
13
|
+
|
|
14
|
+
from plotroom.core.events import LedgerError
|
|
15
|
+
from plotroom.core.search_sources import EVENT_KINDS, event_record
|
|
16
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
17
|
+
from plotroom.ports.search import (
|
|
18
|
+
BackfillPage,
|
|
19
|
+
BackfillPosition,
|
|
20
|
+
BackfillSource,
|
|
21
|
+
EmbeddedRecord,
|
|
22
|
+
Embedder,
|
|
23
|
+
EmbeddingError,
|
|
24
|
+
EmbeddingIndex,
|
|
25
|
+
EmbeddingPending,
|
|
26
|
+
EmbeddingReadiness,
|
|
27
|
+
EmbeddingRejection,
|
|
28
|
+
IndexedEmbedding,
|
|
29
|
+
RejectedRecord,
|
|
30
|
+
Search,
|
|
31
|
+
SearchBackfill,
|
|
32
|
+
SearchPage,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from plotroom.core.ledger import Ledger
|
|
37
|
+
|
|
38
|
+
log = logging.getLogger("plotroom.search")
|
|
39
|
+
EMBEDDING_BATCH_SIZE = 32
|
|
40
|
+
BACKFILL_BATCH_SIZE = 32
|
|
41
|
+
_WRITE_RETRY_DELAYS = (0.1, 0.5, 1.0)
|
|
42
|
+
type WriteErrorClassifier = Callable[[Exception], str | None]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def _commit_search_write(
|
|
46
|
+
ledger: Ledger,
|
|
47
|
+
source: str,
|
|
48
|
+
work: Callable[[UnitOfWork], Awaitable[bool]],
|
|
49
|
+
retryable_write_error: WriteErrorClassifier | None,
|
|
50
|
+
) -> bool:
|
|
51
|
+
"""Retry a whole cursor-checked write outside the writer task."""
|
|
52
|
+
if retryable_write_error is None:
|
|
53
|
+
await ledger.run("system", work)
|
|
54
|
+
return True
|
|
55
|
+
|
|
56
|
+
failure_code = None
|
|
57
|
+
for attempt, delay in enumerate((*_WRITE_RETRY_DELAYS, None), start=1):
|
|
58
|
+
fields = {"project": ledger.project_id, "source": source, "attempt": attempt}
|
|
59
|
+
try:
|
|
60
|
+
await ledger.run("system", work)
|
|
61
|
+
except Exception as error:
|
|
62
|
+
failure_code = retryable_write_error(error)
|
|
63
|
+
if failure_code is None or delay is None:
|
|
64
|
+
log.error(
|
|
65
|
+
"search write stopped",
|
|
66
|
+
extra={**fields, "failure_code": failure_code or "search_write_failed"},
|
|
67
|
+
)
|
|
68
|
+
return False
|
|
69
|
+
log.warning("search write will retry", extra={**fields, "failure_code": failure_code})
|
|
70
|
+
await asyncio.sleep(delay)
|
|
71
|
+
else:
|
|
72
|
+
if failure_code is not None:
|
|
73
|
+
log.info("search write recovered", extra={**fields, "failure_code": failure_code})
|
|
74
|
+
return True
|
|
75
|
+
raise AssertionError("search write retry schedule must terminate")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class _Sequenced(Protocol):
|
|
79
|
+
@property
|
|
80
|
+
def seq(self) -> int: ...
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def committed_batches[T: _Sequenced](
|
|
84
|
+
ledger: Ledger,
|
|
85
|
+
read_cursor: Callable[[], Awaitable[int | None]],
|
|
86
|
+
read_page: Callable[[int, int], Awaitable[list[T]]],
|
|
87
|
+
*,
|
|
88
|
+
limit: int,
|
|
89
|
+
through: int | None = None,
|
|
90
|
+
) -> AsyncIterator[tuple[int, list[T]]]:
|
|
91
|
+
"""Follow commits, or yield one final empty page at a finite historical boundary."""
|
|
92
|
+
while True:
|
|
93
|
+
committed = ledger.commit_signal
|
|
94
|
+
after = await read_cursor()
|
|
95
|
+
if after is None:
|
|
96
|
+
return
|
|
97
|
+
records = await read_page(after, limit)
|
|
98
|
+
if through is not None:
|
|
99
|
+
records = [record for record in records if record.seq <= through]
|
|
100
|
+
if records:
|
|
101
|
+
yield after, records
|
|
102
|
+
elif through is not None:
|
|
103
|
+
yield after, []
|
|
104
|
+
return
|
|
105
|
+
else:
|
|
106
|
+
await committed.wait()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def backfill_search(
|
|
110
|
+
ledger: Ledger,
|
|
111
|
+
index: SearchBackfill,
|
|
112
|
+
*,
|
|
113
|
+
limit: int = BACKFILL_BATCH_SIZE,
|
|
114
|
+
retryable_write_error: WriteErrorClassifier | None = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
"""Backfill one project's retained sources in small, independently committed pages."""
|
|
117
|
+
if index.project_id != ledger.project_id:
|
|
118
|
+
raise ValueError("search backfill must belong to the current project")
|
|
119
|
+
if limit < 1:
|
|
120
|
+
raise ValueError("search backfill requires a positive page size")
|
|
121
|
+
|
|
122
|
+
async def commit(
|
|
123
|
+
source: BackfillSource, expected: BackfillPosition, page: BackfillPage
|
|
124
|
+
) -> bool:
|
|
125
|
+
return await _commit_search_write(
|
|
126
|
+
ledger,
|
|
127
|
+
f"backfill.{source}",
|
|
128
|
+
partial(
|
|
129
|
+
UnitOfWork.save_search_backfill,
|
|
130
|
+
index=index,
|
|
131
|
+
source=source,
|
|
132
|
+
expected=expected,
|
|
133
|
+
page=page,
|
|
134
|
+
),
|
|
135
|
+
retryable_write_error,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
async def event_cursor() -> int | None:
|
|
139
|
+
position = await index.backfill_position(BackfillSource.EVENTS)
|
|
140
|
+
if position is None:
|
|
141
|
+
return None
|
|
142
|
+
return int(position[0]) if position else 0
|
|
143
|
+
|
|
144
|
+
through = await ledger.head_seq()
|
|
145
|
+
while await event_cursor() is not None:
|
|
146
|
+
async for after, events in committed_batches(
|
|
147
|
+
ledger, event_cursor, ledger.events_after, limit=limit, through=through
|
|
148
|
+
):
|
|
149
|
+
position = (after,) if after else ()
|
|
150
|
+
page = BackfillPage(
|
|
151
|
+
(events[-1].seq,) if events else None,
|
|
152
|
+
tuple(event_record(event) for event in events if event.kind in EVENT_KINDS),
|
|
153
|
+
)
|
|
154
|
+
if not await commit(BackfillSource.EVENTS, position, page):
|
|
155
|
+
return
|
|
156
|
+
|
|
157
|
+
for source in (
|
|
158
|
+
BackfillSource.DECISIONS,
|
|
159
|
+
BackfillSource.ASKS,
|
|
160
|
+
BackfillSource.COMMENTS,
|
|
161
|
+
BackfillSource.PULLS,
|
|
162
|
+
):
|
|
163
|
+
while (position := await index.backfill_position(source)) is not None:
|
|
164
|
+
page = await index.backfill_page(source, position, limit)
|
|
165
|
+
if not await commit(source, position, page):
|
|
166
|
+
return
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def pack_vector(vector: tuple[float, ...], dimension: int) -> bytes:
|
|
170
|
+
try:
|
|
171
|
+
if len(vector) != dimension or not all(math.isfinite(value) for value in vector):
|
|
172
|
+
raise EmbeddingError("embedding vector has an invalid dimension or value")
|
|
173
|
+
return struct.pack(f"<{dimension}f", *vector)
|
|
174
|
+
except (OverflowError, struct.error) as exc:
|
|
175
|
+
raise EmbeddingError("embedding vector has a value outside float32 range") from exc
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def follow_search_embeddings(
|
|
179
|
+
ledger: Ledger,
|
|
180
|
+
index: EmbeddingIndex,
|
|
181
|
+
embedder: Embedder,
|
|
182
|
+
*,
|
|
183
|
+
retry_seconds: float = 5,
|
|
184
|
+
retryable_write_error: WriteErrorClassifier | None = None,
|
|
185
|
+
) -> None:
|
|
186
|
+
if index.project_id != ledger.project_id:
|
|
187
|
+
raise ValueError("embedding index must belong to the current project")
|
|
188
|
+
async for after, revisions in committed_batches(
|
|
189
|
+
ledger, index.cursor, index.revisions_after, limit=EMBEDDING_BATCH_SIZE
|
|
190
|
+
):
|
|
191
|
+
pending = [(item.seq, item.record) for item in revisions if item.record is not None]
|
|
192
|
+
records: tuple[IndexedEmbedding, ...] = ()
|
|
193
|
+
if pending:
|
|
194
|
+
try:
|
|
195
|
+
outcomes = await embedder.embed(tuple(record.body for _, record in pending))
|
|
196
|
+
if len(outcomes) != len(pending):
|
|
197
|
+
raise EmbeddingError("embedding batch has an invalid outcome count")
|
|
198
|
+
records = tuple(
|
|
199
|
+
RejectedRecord(seq, record.kind, record.id, outcome)
|
|
200
|
+
if isinstance(outcome, EmbeddingRejection)
|
|
201
|
+
else EmbeddedRecord(
|
|
202
|
+
seq, record.kind, record.id, pack_vector(outcome, index.model.dimension)
|
|
203
|
+
)
|
|
204
|
+
for (seq, record), outcome in zip(pending, outcomes, strict=True)
|
|
205
|
+
)
|
|
206
|
+
except EmbeddingError:
|
|
207
|
+
log.warning(
|
|
208
|
+
"embedding batch will retry",
|
|
209
|
+
extra={"project": ledger.project_id},
|
|
210
|
+
)
|
|
211
|
+
await asyncio.sleep(retry_seconds)
|
|
212
|
+
continue
|
|
213
|
+
|
|
214
|
+
if not await _commit_search_write(
|
|
215
|
+
ledger,
|
|
216
|
+
"embeddings",
|
|
217
|
+
partial(
|
|
218
|
+
UnitOfWork.save_embedding_batch,
|
|
219
|
+
index=index,
|
|
220
|
+
expected=after,
|
|
221
|
+
through=revisions[-1].seq,
|
|
222
|
+
records=records,
|
|
223
|
+
),
|
|
224
|
+
retryable_write_error,
|
|
225
|
+
):
|
|
226
|
+
return
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@dataclass(frozen=True)
|
|
230
|
+
class SemanticSearch:
|
|
231
|
+
index: EmbeddingIndex
|
|
232
|
+
embedder: Embedder
|
|
233
|
+
|
|
234
|
+
async def query(
|
|
235
|
+
self, lexical: Search, project: str, text: str, kinds: tuple[str, ...], limit: int
|
|
236
|
+
) -> SearchPage:
|
|
237
|
+
try:
|
|
238
|
+
readiness = await self.index.preflight(kinds, text)
|
|
239
|
+
if readiness is EmbeddingReadiness.REJECTED_MATCH:
|
|
240
|
+
page = await lexical.query(project, text, kinds, limit)
|
|
241
|
+
return replace(page, mode="lexical", fallback_reason="embedding_rejected")
|
|
242
|
+
if readiness is EmbeddingReadiness.PENDING:
|
|
243
|
+
raise EmbeddingPending
|
|
244
|
+
if readiness is EmbeddingReadiness.EMPTY:
|
|
245
|
+
return SearchPage((), 0, mode="semantic")
|
|
246
|
+
outcomes = await self.embedder.embed((text,))
|
|
247
|
+
if len(outcomes) != 1:
|
|
248
|
+
raise EmbeddingError("search query requires exactly one embedding")
|
|
249
|
+
vector = outcomes[0]
|
|
250
|
+
if isinstance(vector, EmbeddingRejection):
|
|
251
|
+
page = await lexical.query(project, text, kinds, limit)
|
|
252
|
+
return replace(page, mode="lexical", fallback_reason="query_rejected")
|
|
253
|
+
# Keep malformed provider values in the provider failure path.
|
|
254
|
+
pack_vector(vector, self.index.model.dimension)
|
|
255
|
+
page = await self.index.query_vector(project, vector, limit, kinds=kinds, text=text)
|
|
256
|
+
return replace(page, mode="semantic") if page.mode is None else page
|
|
257
|
+
except EmbeddingPending:
|
|
258
|
+
reason = "index_pending"
|
|
259
|
+
except EmbeddingError:
|
|
260
|
+
reason = "provider_unavailable"
|
|
261
|
+
except LedgerError as exc:
|
|
262
|
+
if exc.code != "unavailable":
|
|
263
|
+
raise
|
|
264
|
+
reason = "vector_unavailable"
|
|
265
|
+
page = await lexical.query(project, text, kinds, limit)
|
|
266
|
+
return replace(page, mode="lexical", fallback_reason=reason)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Convert local event and projection sources to stable searchable records."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from plotroom.core.intake import SESSION_MESSAGE, TURN_REPORT
|
|
8
|
+
from plotroom.core.merge_flakes import FLAKE_EVENT
|
|
9
|
+
from plotroom.ports.search import (
|
|
10
|
+
ASK_KIND,
|
|
11
|
+
DECISION_KIND,
|
|
12
|
+
ISSUE_COMMENT_KIND,
|
|
13
|
+
MESSAGE_KIND,
|
|
14
|
+
PR_BODY_KIND,
|
|
15
|
+
SearchRecord,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from plotroom.core.ask_checks import Ask
|
|
20
|
+
from plotroom.core.events import Event
|
|
21
|
+
from plotroom.core.github import PullRequest
|
|
22
|
+
from plotroom.core.github_projection import GitHubRecord, GitHubResource
|
|
23
|
+
from plotroom.core.human_queue import Decision
|
|
24
|
+
|
|
25
|
+
EVENT_KINDS = frozenset({MESSAGE_KIND, SESSION_MESSAGE, TURN_REPORT, FLAKE_EVENT})
|
|
26
|
+
PRIVATE_KINDS = frozenset({DECISION_KIND, ASK_KIND})
|
|
27
|
+
SEARCH_KINDS = EVENT_KINDS | PRIVATE_KINDS | {ISSUE_COMMENT_KIND, PR_BODY_KIND}
|
|
28
|
+
FLAKE_TEXT_FIELDS = (
|
|
29
|
+
"check_name",
|
|
30
|
+
"pattern",
|
|
31
|
+
"test_id",
|
|
32
|
+
"path",
|
|
33
|
+
"repository",
|
|
34
|
+
"head_sha",
|
|
35
|
+
"check_id",
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def event_record(event: Event) -> SearchRecord:
|
|
40
|
+
body = event.body
|
|
41
|
+
if event.kind == FLAKE_EVENT:
|
|
42
|
+
body = "\n".join(
|
|
43
|
+
[body, *(str(event.fields[key]) for key in FLAKE_TEXT_FIELDS if key in event.fields)]
|
|
44
|
+
).lstrip("\n")
|
|
45
|
+
return SearchRecord(event.kind, event.id, body)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def decision_record(decision: Decision) -> SearchRecord:
|
|
49
|
+
return SearchRecord(DECISION_KIND, decision.decision_id, decision.exact_words)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def ask_record(ask: Ask) -> SearchRecord:
|
|
53
|
+
return SearchRecord(ASK_KIND, ask.ask_id, ask.text)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def comment_record(repository: str, comment: GitHubRecord) -> SearchRecord:
|
|
57
|
+
record_id = f"{repository}#{comment.fields['number']}#issuecomment-{comment.fields['id']}"
|
|
58
|
+
return SearchRecord(ISSUE_COMMENT_KIND, record_id, comment.body)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def pull_body_record(
|
|
62
|
+
repository: str, number: int, body: str, *, provisional: bool = False
|
|
63
|
+
) -> SearchRecord:
|
|
64
|
+
return SearchRecord(PR_BODY_KIND, f"{repository}#{number}", body, provisional=provisional)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def pull_text_record(
|
|
68
|
+
pull: PullRequest,
|
|
69
|
+
resource: GitHubResource,
|
|
70
|
+
*,
|
|
71
|
+
updated_since: str | None = None,
|
|
72
|
+
allow_incomplete: bool = False,
|
|
73
|
+
) -> SearchRecord | None:
|
|
74
|
+
attributes = resource.attributes
|
|
75
|
+
body = attributes.get("body")
|
|
76
|
+
updated_at = attributes.get("pull_updated_at")
|
|
77
|
+
if (
|
|
78
|
+
(resource.complete or allow_incomplete)
|
|
79
|
+
and isinstance(body, str)
|
|
80
|
+
and isinstance(updated_at, str)
|
|
81
|
+
and attributes.get("head_sha") == pull.head_sha
|
|
82
|
+
and type(attributes.get("pull_version")) is int
|
|
83
|
+
and attributes["pull_version"] == pull.version
|
|
84
|
+
and (updated_since if updated_since is not None else pull.updated_at)
|
|
85
|
+
<= updated_at
|
|
86
|
+
<= pull.updated_at
|
|
87
|
+
):
|
|
88
|
+
return pull_body_record(
|
|
89
|
+
pull.repository,
|
|
90
|
+
pull.number,
|
|
91
|
+
body,
|
|
92
|
+
provisional=not pull.complete or updated_at != pull.updated_at,
|
|
93
|
+
)
|
|
94
|
+
return None
|