From 90775c5e65e12a5046d1cd2bb4802df758e647da Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 09:38:47 -0500 Subject: [PATCH] Split BusReader and HistoricalBusReader out of MessageBus for read-only CLI verbs --- src/agent_comms/cli_verbs/history.py | 6 +- src/agent_comms/cli_verbs/inbox.py | 7 +- src/agent_comms/cli_verbs/threads.py | 5 +- src/agent_comms/messaging/bus_reader.py | 259 ++++++++++++++++++ src/agent_comms/messaging/historical_views.py | 9 + src/agent_comms/messaging/message_bus.py | 256 +---------------- src/agent_comms/messaging/published_bus.py | 18 +- tests/test_revision_owner_annotations.py | 4 +- 8 files changed, 298 insertions(+), 266 deletions(-) create mode 100644 src/agent_comms/messaging/bus_reader.py diff --git a/src/agent_comms/cli_verbs/history.py b/src/agent_comms/cli_verbs/history.py index 8bb4094208..c1c7f714f7 100644 --- a/src/agent_comms/cli_verbs/history.py +++ b/src/agent_comms/cli_verbs/history.py @@ -8,17 +8,15 @@ from agent_comms.installer.active_route import CommsRoute from agent_comms.messaging.channel_targets import CommandTarget from agent_comms.messaging.channels import AnyChannel -from agent_comms.messaging.historical_views import HistoryView +from agent_comms.messaging.historical_views import HistoricalBusReader, HistoryView from agent_comms.messaging.history_result import ( ChannelHistoryPageResult, DmHistoryPageResult, EverythingHistoryPageResult, HistoryPageResult, ) -from agent_comms.messaging.message_bus import MessageBus from agent_comms.messaging.message_page import PageBounds from agent_comms.messaging.page_traversal import NewestCursor, PageCursor -from agent_comms.messaging.publisher import OwnerPublisher from agent_comms.messaging.read_basis import AnonymousViewer, DisplayViewer from agent_comms.nominal.field_codec import Argument from agent_comms.planning.goal_snapshot_reader import GoalSnapshotReader @@ -76,7 +74,7 @@ def apply(self, ctx: CliBus) -> HistoryPageResult: def execute(self, route: CommsRoute, output: TextIO, open_bus: BusOpener) -> int: with ActivityClient.client(route) as client: - bus = MessageBus(client.root, client.registry, OwnerPublisher) + bus = HistoricalBusReader(client.root, client.registry) goals = GoalSnapshotReader(client.root, client.agents) presentation = BusPresentation( bus, client.registry, ChannelCatalog.at(client.root), client.agents, goals, diff --git a/src/agent_comms/cli_verbs/inbox.py b/src/agent_comms/cli_verbs/inbox.py index 8275893a5c..2b9248850f 100644 --- a/src/agent_comms/cli_verbs/inbox.py +++ b/src/agent_comms/cli_verbs/inbox.py @@ -8,11 +8,10 @@ from agent_comms.cli_verbs.cli_commands import ThreadArgument from agent_comms.cli_verbs.cli_result import CliResult from agent_comms.installer.active_route import CommsRoute +from agent_comms.messaging.bus_reader import BusReader from agent_comms.messaging.history_result import HistoryPageResult -from agent_comms.messaging.message_bus import MessageBus from agent_comms.messaging.message_reference import NewestUnreadStart from agent_comms.messaging.page_traversal import NewestCursor, PageCursor -from agent_comms.messaging.publisher import OwnerPublisher from agent_comms.nominal.field_codec import Argument from agent_comms.registry.route_client import RouteClient @@ -38,7 +37,7 @@ class InboxCliCommand(ThreadArgument, CliCommand): ), ] = NewestCursor() - def _read(self, bus: MessageBus) -> InboxResult: + def _read(self, bus: BusReader) -> InboxResult: inbox = bus.inbox(self.thread, after=NewestUnreadStart(self.before)) shown = tuple(reversed(inbox.page.messages)) return InboxResult(shown, inbox.page.has_older, len(shown) + inbox.remaining) @@ -48,5 +47,5 @@ def apply(self, ctx: CliBus) -> CliResult: def execute(self, route: CommsRoute, output: TextIO, open_bus: BusOpener) -> int: with RouteClient.client(route) as client: - bus = MessageBus(client.root, client.registry, OwnerPublisher) + bus = BusReader(client.root, client.registry) return self._read(bus).write(output) diff --git a/src/agent_comms/cli_verbs/threads.py b/src/agent_comms/cli_verbs/threads.py index f8f09542e7..1354ed2805 100644 --- a/src/agent_comms/cli_verbs/threads.py +++ b/src/agent_comms/cli_verbs/threads.py @@ -6,8 +6,7 @@ from agent_comms.cli_verbs.cli_verb import BusOpener, CliBus, CliCommand from agent_comms.cli_verbs.cli_result import CliResult from agent_comms.installer.active_route import CommsRoute -from agent_comms.messaging.message_bus import MessageBus -from agent_comms.messaging.publisher import OwnerPublisher +from agent_comms.messaging.bus_reader import BusReader from agent_comms.nominal.field_codec import Argument, WireForm from agent_comms.planning.goal_snapshot_reader import GoalSnapshotReader from agent_comms.thread_views import ThreadRecord @@ -31,7 +30,7 @@ def apply(self, ctx: CliBus) -> ThreadsResult: def execute(self, route: CommsRoute, output: TextIO, open_bus: BusOpener) -> int: with ActivityClient.client(route) as client: - bus = MessageBus(client.root, client.registry, OwnerPublisher) + bus = BusReader(client.root, client.registry) goals = GoalSnapshotReader(client.root, client.agents) return ThreadsResult(ThreadRecord.list_threads( client.registry.snapshot(), bus, client.agents, goals, active_only=self.active_only, diff --git a/src/agent_comms/messaging/bus_reader.py b/src/agent_comms/messaging/bus_reader.py new file mode 100644 index 0000000000..a9c01438c2 --- /dev/null +++ b/src/agent_comms/messaging/bus_reader.py @@ -0,0 +1,259 @@ +"""Read-only bus snapshots, unread counts, inbox pages, and display read marks.""" + +from __future__ import annotations + +import threading +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from functools import partial +from pathlib import Path + +from agent_comms.messaging.bus import Bus, BusSnapshot +from agent_comms.messaging.bus_read_source import BusReadSource +from agent_comms.messaging.bus_route_counts import HeldUnseenCounts +from agent_comms.messaging.channel_targets import NamedTarget +from agent_comms.messaging.channels import AnyChannel, Channel +from agent_comms.messaging.message_page import ( + DisplayedMessagePage, + InboxPage, + MessagePageRequest, + PageBounds, +) +from agent_comms.messaging.message_reference import FirstUnreadStart, InboxStart, NewestUnreadStart +from agent_comms.messaging.messages import Message +from agent_comms.messaging.published_bus import BusCatalog +from agent_comms.messaging.read_basis import ( + AnonymousViewer, + Conversation, + DisplayBasis, + DisplayedConversation, + DisplayViewer, + ListedDeliveries, + NamedViewer, + ReadCursor, +) +from agent_comms.messaging.read_ledger import ReadDocument, ReadLedger +from agent_comms.messaging.read_selection import CapturedSelection +from agent_comms.messaging.recorded_bus import RecordedBus +from agent_comms.messaging.routing import DeliveryScope +from agent_comms.registry.catalog_document import CatalogDocument +from agent_comms.registry.catalog_store import ChannelCatalog +from agent_comms.registry.registration import Registration +from agent_comms.registry.registry_document import RegistrySnapshot +from agent_comms.storage.file_observation import FileIdentity + + +@dataclass(frozen=True, slots=True) +class _CachedPendingProjection: + held: HeldUnseenCounts + registry: RegistrySnapshot + catalog: CatalogDocument + document: ReadDocument + actors: frozenset[str] + + def same_cut(self, basis: CapturedSelection) -> bool: + return ( + self.registry is basis.registry + and self.catalog is basis.catalog + and self.document is basis.document + ) + + def serves(self, basis: CapturedSelection, actor_set: frozenset[str], source: BusSnapshot) -> bool: + return ( + self.same_cut(basis) + and actor_set <= self.actors + and source.revision() == self.held.through + ) + + +_pending_counts_lock = threading.Lock() +_pending_counts_cache: dict[tuple[Path, FileIdentity], _CachedPendingProjection] = {} + + +@dataclass(frozen=True) +class UnreadCut: + """One unread page's rows in one source cut; a count of the rest must read the same cut.""" + + source: BusSnapshot + snapshot: RegistrySnapshot + require_channel: Callable[[str], Channel] + delivery: DeliveryScope + seen: ReadCursor + cursor: int + request: MessagePageRequest + document: ReadDocument + + def counts(self) -> dict[str, int]: + """Inside the cut: what is pending for this thread, per conversation.""" + actor = self.delivery.actor + counts: dict[str, int] = self.source.unseen_counts( + self.snapshot, {actor: self.delivery}, {actor: self.seen}, after=self.cursor, + )[actor] + return counts + + +class BusReader(BusCatalog, BusReadSource): + """Live read-only bus access independent of publication, history archive, and coordination.""" + + def __init__(self, root: Path, registry: Registration): + self.bus = Bus(Bus.path_in(root)) + self.reads = ReadLedger.at(root) + self._registry = registry + self._channels = ChannelCatalog.at(root) + self._pending = HeldUnseenCounts() + + @contextmanager + def snapshot(self, viewer: DisplayViewer = AnonymousViewer()) -> Iterator[tuple[CapturedSelection, BusSnapshot]]: + with self.bus.reading() as source: + basis = CapturedSelection.load( + self._registry, self._channels, self.reads, viewer, source.activity_clocks(), + ) + yield basis, source + + def inbox( + self, name: str, target: NamedTarget = AnyChannel.target(), *, + after: InboxStart = NewestUnreadStart(), bounds: PageBounds = PageBounds(), + ) -> InboxPage: + """A glance at a thread's unread messages: newest first, with the unread beyond them.""" + return self.inbox_at(name, self._registry.snapshot(), target, after=after, bounds=bounds) + + def inbox_at( + self, name: str, snapshot: RegistrySnapshot, target: NamedTarget = AnyChannel.target(), *, + after: InboxStart = FirstUnreadStart(), bounds: PageBounds = PageBounds(), + ) -> InboxPage: + with self._unread_cut(name, snapshot, target, after, bounds) as cut: + counts = cut.counts() + result = self._displayed(cut) + total = target.pending_count(counts, snapshot, cut.require_channel) + return InboxPage(result.page, result.displayed, total - len(result.page.messages)) + + def untaken_at( + self, name: str, snapshot: RegistrySnapshot, target: NamedTarget = AnyChannel.target(), *, + after: InboxStart = FirstUnreadStart(), bounds: PageBounds = PageBounds(), + ) -> DisplayedMessagePage: + """The page alone. A watch wakes on every bus commit and never reads the remainder: + counting it was a second full route query per empty wake per open socket.""" + with self._unread_cut(name, snapshot, target, after, bounds) as cut: + pass + return self._displayed(cut) + + def _displayed(self, cut: UnreadCut) -> DisplayedMessagePage: + page: DisplayedMessagePage = cut.request.displayed( + self.reads, cut.document, cut.delivery.actor, cut.snapshot, cut.snapshot, self.bus, + ) + return page + + @contextmanager + def _unread_cut( + self, name: str, snapshot: RegistrySnapshot, target: NamedTarget, after: InboxStart, + bounds: PageBounds, + ) -> Iterator[UnreadCut]: + catalog = self._channels.read_shared() + require_channel = partial(self.channel_in, catalog) + delivery = DeliveryScope.capture(name, snapshot, catalog) + selection = delivery.selection(target, snapshot, require_channel) + document, seen = after.read_basis(self.reads, delivery.actor, snapshot) + self.bus.messages_for_references(after.references()) + cursor = after.cursor() + traversal = after.traversal() + with self.bus.reading() as source: + with source.observing() as db: + seen = seen.attached(db, self.bus.path.parent, self._registry.store.privacy()) + unread = source.unseen_deliveries( + snapshot, delivery, seen, after=cursor, scope=selection, limit=bounds.limit + 1, + traversal=traversal, + ) + yield UnreadCut( + source, snapshot, require_channel, delivery, seen, cursor, + MessagePageRequest.listed( + ListedDeliveries(selection, frozenset(row.seq for row in unread), + frozenset(row.target for row in unread)), + PageBounds(traversal, bounds.limit), + ), document, + ) + + def pending_count(self, name: str, target: NamedTarget = AnyChannel.target()) -> int: + with self.snapshot() as (basis, source): + counts = self._pending_projection(source, basis, [name])[name] + return target.pending_count(counts, basis.registry, + lambda name: basis.catalog.require_channel(name, basis.activity)) + + def pending_counts_all(self, names: Sequence[str]) -> Mapping[str, int]: + if not names: + return {} + with self.snapshot() as (basis, source): + return {name: sum(counts.values()) + for name, counts in self._pending_projection(source, basis, names).items()} + + def _pending_projection(self, source: BusSnapshot, basis: CapturedSelection, names: Sequence[str]): + actors = {name: basis.registry.canonical_name(name) for name in names} + actor_set = frozenset(actors.values()) + cache_key = (self.bus.path, source.identity) + with _pending_counts_lock: + cached = _pending_counts_cache.get(cache_key) + if cached is not None and cached.serves(basis, actor_set, source): + return {name: cached.held.counts[actor] for name, actor in actors.items()} + deliveries = {actor: DeliveryScope.capture(actor, basis.registry, basis.catalog) + for actor in actor_set} + seen = {actor: basis.document.cursor(actor, basis.registry, source) + for actor in deliveries} + held = cached.held if cached is not None else HeldUnseenCounts() + updated = source.advanced_unseen_counts(held, basis.registry, deliveries, seen) + with _pending_counts_lock: + _pending_counts_cache[cache_key] = _CachedPendingProjection( + updated, basis.registry, basis.catalog, basis.document, actor_set, + ) + return {name: updated.counts[actor] for name, actor in actors.items()} + + def pending_counts_opened( + self, source: BusSnapshot, selection: CapturedSelection, *, conversations: Iterable[str] = (), + ) -> Mapping[str, int]: + actor = selection.require_viewer() + delivery = DeliveryScope.capture(actor, selection.registry, selection.catalog) + # Every viewer snapshot asks; between two of them only appended rows can be new. + self._pending = source.advanced_unseen_counts( + self._pending, selection.registry, {actor: delivery}, {actor: selection.seen(source)}) + return {**dict.fromkeys(conversations, 0), **self._pending.counts[actor]} + + def mark_read_through( + self, name: str, sequence: int, *, target: NamedTarget = AnyChannel.target(), + ) -> None: + if sequence < 0: + raise ValueError("Delivery sequence cannot be negative.") + with self.snapshot(NamedViewer(name)) as (basis, source): + canonical = basis.require_viewer() + delivery = DeliveryScope.capture(canonical, basis.registry, basis.catalog) + scope = delivery.selection(target, basis.registry, + lambda channel: basis.catalog.require_channel(channel, basis.activity)) + displayed = scope.capture_deliveries( + self.reads, canonical, basis.registry, source, document=basis.document, + audience=delivery, through=sequence, + ) + self.reads.mark_displayed(canonical, displayed) + + def mark_messages_displayed(self, name: str, messages: Sequence[Message]) -> None: + """Advance the read ledger for exactly these delivered messages without skipping others.""" + deliveries = tuple(message for message in messages if message.seq > 0) + if not deliveries: + return + with self.snapshot(NamedViewer(name)) as (basis, source): + canonical = basis.require_viewer() + delivery = DeliveryScope.capture(canonical, basis.registry, basis.catalog) + grouped: dict[Conversation, list[int]] = {} + for message in deliveries: + conversation = delivery.read_key(message.sender, message.target, basis.registry) + grouped.setdefault(conversation, []).append(message.seq) + displayed = DisplayBasis( + canonical, + basis.registry.require(canonical).incarnation.wire_birth, + tuple( + DisplayedConversation(conversation, tuple(sorted(set(sequences)))) + for conversation, sequences in grouped.items() + ), + RecordedBus(source.identity), + ) + self.reads.mark_displayed(canonical, displayed) + + def channels(self) -> Sequence[str]: + return list(self.channel_declarations()) diff --git a/src/agent_comms/messaging/historical_views.py b/src/agent_comms/messaging/historical_views.py index 6f32192fc0..706ba8a97c 100644 --- a/src/agent_comms/messaging/historical_views.py +++ b/src/agent_comms/messaging/historical_views.py @@ -18,6 +18,7 @@ from agent_comms.execution.host_platform import HostPlatform from agent_comms.execution.transcript_routes import TranscriptRoutes from agent_comms.messaging.bus import Bus +from agent_comms.messaging.bus_reader import BusReader from agent_comms.messaging.channel_targets import CommandTarget, NamedTarget, ThreadTarget from agent_comms.messaging.channels import Channel from agent_comms.messaging.display_references import ( @@ -803,3 +804,11 @@ def threads(self, senders: HistoricalSenders) -> tuple[HistoricalThread, ...]: for thread in source.provenance.threads.values() if senders.includes(thread, source.provenance)) return tuple(result) + + +class HistoricalBusReader(BusReader): + """Read-only bus access with its historical archive, independent of publication.""" + + def __init__(self, root: Path, registry): + super().__init__(root, registry) + self.history = HistoryArchive.at(self.bus.path.parent) diff --git a/src/agent_comms/messaging/message_bus.py b/src/agent_comms/messaging/message_bus.py index f9685d8a34..30f54480a6 100644 --- a/src/agent_comms/messaging/message_bus.py +++ b/src/agent_comms/messaging/message_bus.py @@ -1,188 +1,33 @@ from __future__ import annotations import inspect -import threading import time -from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping, Sequence -from contextlib import aclosing, contextmanager -from dataclasses import dataclass -from functools import partial +from collections.abc import Awaitable, Callable, Sequence +from contextlib import aclosing from pathlib import Path from agent_comms.coordination.work import CoordinationWork -from agent_comms.messaging.bus import Bus, BusSnapshot -from agent_comms.messaging.bus_read_source import BusReadSource -from agent_comms.messaging.bus_route_counts import HeldUnseenCounts -from agent_comms.messaging.channel_targets import NamedTarget -from agent_comms.messaging.channels import AnyChannel, Channel -from agent_comms.messaging.historical_views import HistoryArchive, SenderFilteredHistory -from agent_comms.messaging.message_page import ( - DisplayedMessagePage, - InboxPage, - MessagePageRequest, - PageBounds, -) -from agent_comms.messaging.message_reference import FirstUnreadStart, InboxStart, NewestUnreadStart +from agent_comms.messaging.bus import Bus +from agent_comms.messaging.historical_views import HistoricalBusReader, SenderFilteredHistory +from agent_comms.messaging.message_page import PageBounds from agent_comms.messaging.messages import Message from agent_comms.messaging.published_bus import PublishedBus from agent_comms.messaging.publisher import Publisher -from agent_comms.messaging.read_basis import ( - AnonymousViewer, - ChannelDisplayScope, - Conversation, - DisplayBasis, - DisplayedConversation, - DisplayViewer, - ListedDeliveries, - NamedViewer, - ReadCursor, - SenderDisplayScope, -) -from agent_comms.messaging.recorded_bus import RecordedBus -from agent_comms.messaging.read_ledger import ReadDocument, ReadLedger -from agent_comms.messaging.read_selection import CapturedSelection -from agent_comms.messaging.routing import DeliveryScope +from agent_comms.messaging.read_basis import ChannelDisplayScope, SenderDisplayScope from agent_comms.messaging.watched import FileSource -from agent_comms.registry.catalog_document import CatalogDocument -from agent_comms.registry.catalog_store import ChannelCatalog from agent_comms.registry.registration import Registration from agent_comms.registry.registry_document import RegistrySnapshot from agent_comms.registry.threads import Thread -from agent_comms.storage.file_observation import FileIdentity from agent_comms.storage.maintenance_barrier import MaintenanceBarrier, MaintenanceHeldError -@dataclass(frozen=True, slots=True) -class _CachedPendingProjection: - held: HeldUnseenCounts - registry: RegistrySnapshot - catalog: CatalogDocument - document: ReadDocument - actors: frozenset[str] - - def same_cut(self, basis: CapturedSelection) -> bool: - return ( - self.registry is basis.registry - and self.catalog is basis.catalog - and self.document is basis.document - ) - - def serves(self, basis: CapturedSelection, actor_set: frozenset[str], source: BusSnapshot) -> bool: - return ( - self.same_cut(basis) - and actor_set <= self.actors - and source.revision() == self.held.through - ) - - -_pending_counts_lock = threading.Lock() -_pending_counts_cache: dict[tuple[Path, FileIdentity], _CachedPendingProjection] = {} - - -@dataclass(frozen=True) -class UnreadCut: - """One unread page's rows in one source cut; a count of the rest must read the same cut.""" - - source: BusSnapshot - snapshot: RegistrySnapshot - require_channel: Callable[[str], Channel] - delivery: DeliveryScope - seen: ReadCursor - cursor: int - request: MessagePageRequest - document: ReadDocument - - def counts(self) -> dict[str, int]: - """Inside the cut: what is pending for this thread, per conversation.""" - actor = self.delivery.actor - counts: dict[str, int] = self.source.unseen_counts( - self.snapshot, {actor: self.delivery}, {actor: self.seen}, after=self.cursor, - )[actor] - return counts - - -class MessageBus[Writes: Publisher](PublishedBus[Writes], BusReadSource): +class MessageBus[Writes: Publisher](PublishedBus[Writes], HistoricalBusReader): def __init__( self, root: Path, registry: Registration, publisher: type[Writes], ): - self.bus = Bus(Bus.path_in(root)) - self.reads = ReadLedger.at(root) - self.history = HistoryArchive.at(self.bus.path.parent) - self._registry = registry - self._channels = ChannelCatalog.at(root) - self._pending = HeldUnseenCounts() + HistoricalBusReader.__init__(self, root, registry) self.publisher = publisher(self.bus, registry, self._channels, self.opened_activity) - @contextmanager - def snapshot(self, viewer: DisplayViewer = AnonymousViewer()) -> Iterator[tuple[CapturedSelection, BusSnapshot]]: - with self.bus.reading() as source: - basis = CapturedSelection.load( - self._registry, self._channels, self.reads, viewer, source.activity_clocks(), - ) - yield basis, source - - def inbox( - self, name: str, target: NamedTarget = AnyChannel.target(), *, - after: InboxStart = NewestUnreadStart(), bounds: PageBounds = PageBounds(), - ) -> InboxPage: - """A glance at a thread's unread messages: newest first, with the unread beyond them.""" - return self.inbox_at(name, self._registry.snapshot(), target, after=after, bounds=bounds) - - def inbox_at( - self, name: str, snapshot: RegistrySnapshot, target: NamedTarget = AnyChannel.target(), *, - after: InboxStart = FirstUnreadStart(), bounds: PageBounds = PageBounds(), - ) -> InboxPage: - with self._unread_cut(name, snapshot, target, after, bounds) as cut: - counts = cut.counts() - result = self._displayed(cut) - total = target.pending_count(counts, snapshot, cut.require_channel) - return InboxPage(result.page, result.displayed, total - len(result.page.messages)) - - def untaken_at( - self, name: str, snapshot: RegistrySnapshot, target: NamedTarget = AnyChannel.target(), *, - after: InboxStart = FirstUnreadStart(), bounds: PageBounds = PageBounds(), - ) -> DisplayedMessagePage: - """The page alone. A watch wakes on every bus commit and never reads the remainder: - counting it was a second full route query per empty wake per open socket.""" - with self._unread_cut(name, snapshot, target, after, bounds) as cut: - pass - return self._displayed(cut) - - def _displayed(self, cut: UnreadCut) -> DisplayedMessagePage: - page: DisplayedMessagePage = cut.request.displayed( - self.reads, cut.document, cut.delivery.actor, cut.snapshot, cut.snapshot, self.bus, - ) - return page - - @contextmanager - def _unread_cut( - self, name: str, snapshot: RegistrySnapshot, target: NamedTarget, after: InboxStart, - bounds: PageBounds, - ) -> Iterator[UnreadCut]: - catalog = self._channels.read_shared() - require_channel = partial(self.channel_in, catalog) - delivery = DeliveryScope.capture(name, snapshot, catalog) - selection = delivery.selection(target, snapshot, require_channel) - document, seen = after.read_basis(self.reads, delivery.actor, snapshot) - self.bus.messages_for_references(after.references()) - cursor = after.cursor() - traversal = after.traversal() - with self.bus.reading() as source: - with source.observing() as db: - seen = seen.attached(db, self.bus.path.parent, self._registry.store.privacy()) - unread = source.unseen_deliveries( - snapshot, delivery, seen, after=cursor, scope=selection, limit=bounds.limit + 1, - traversal=traversal, - ) - yield UnreadCut( - source, snapshot, require_channel, delivery, seen, cursor, - MessagePageRequest.listed( - ListedDeliveries(selection, frozenset(row.seq for row in unread), - frozenset(row.target for row in unread)), - PageBounds(traversal, bounds.limit), - ), document, - ) - async def when_open[Result](self, operation: Callable[[], Result | Awaitable[Result]]) -> Result: while True: try: @@ -198,91 +43,6 @@ async def resumed(self) -> None: if not maintenance.read().turn_pending: return - def pending_count(self, name: str, target: NamedTarget = AnyChannel.target()) -> int: - with self.snapshot() as (basis, source): - counts = self._pending_projection(source, basis, [name])[name] - return target.pending_count(counts, basis.registry, - lambda name: basis.catalog.require_channel(name, basis.activity)) - - def pending_counts_all(self, names: Sequence[str]) -> Mapping[str, int]: - if not names: - return {} - with self.snapshot() as (basis, source): - return {name: sum(counts.values()) - for name, counts in self._pending_projection(source, basis, names).items()} - - def _pending_projection(self, source: BusSnapshot, basis: CapturedSelection, names: Sequence[str]): - actors = {name: basis.registry.canonical_name(name) for name in names} - actor_set = frozenset(actors.values()) - cache_key = (self.bus.path, source.identity) - with _pending_counts_lock: - cached = _pending_counts_cache.get(cache_key) - if cached is not None and cached.serves(basis, actor_set, source): - return {name: cached.held.counts[actor] for name, actor in actors.items()} - deliveries = {actor: DeliveryScope.capture(actor, basis.registry, basis.catalog) - for actor in actor_set} - seen = {actor: basis.document.cursor(actor, basis.registry, source) - for actor in deliveries} - held = cached.held if cached is not None else HeldUnseenCounts() - updated = source.advanced_unseen_counts(held, basis.registry, deliveries, seen) - with _pending_counts_lock: - _pending_counts_cache[cache_key] = _CachedPendingProjection( - updated, basis.registry, basis.catalog, basis.document, actor_set, - ) - return {name: updated.counts[actor] for name, actor in actors.items()} - - def pending_counts_opened( - self, source: BusSnapshot, selection: CapturedSelection, *, conversations: Iterable[str] = (), - ) -> Mapping[str, int]: - actor = selection.require_viewer() - delivery = DeliveryScope.capture(actor, selection.registry, selection.catalog) - # Every viewer snapshot asks; between two of them only appended rows can be new. - self._pending = source.advanced_unseen_counts( - self._pending, selection.registry, {actor: delivery}, {actor: selection.seen(source)}) - return {**dict.fromkeys(conversations, 0), **self._pending.counts[actor]} - - def mark_read_through( - self, name: str, sequence: int, *, target: NamedTarget = AnyChannel.target(), - ) -> None: - if sequence < 0: - raise ValueError("Delivery sequence cannot be negative.") - with self.snapshot(NamedViewer(name)) as (basis, source): - canonical = basis.require_viewer() - delivery = DeliveryScope.capture(canonical, basis.registry, basis.catalog) - scope = delivery.selection(target, basis.registry, - lambda channel: basis.catalog.require_channel(channel, basis.activity)) - displayed = scope.capture_deliveries( - self.reads, canonical, basis.registry, source, document=basis.document, - audience=delivery, through=sequence, - ) - self.reads.mark_displayed(canonical, displayed) - - def mark_messages_displayed(self, name: str, messages: Sequence[Message]) -> None: - """Advance the read ledger for exactly these delivered messages without skipping others.""" - deliveries = tuple(message for message in messages if message.seq > 0) - if not deliveries: - return - with self.snapshot(NamedViewer(name)) as (basis, source): - canonical = basis.require_viewer() - delivery = DeliveryScope.capture(canonical, basis.registry, basis.catalog) - grouped: dict[Conversation, list[int]] = {} - for message in deliveries: - conversation = delivery.read_key(message.sender, message.target, basis.registry) - grouped.setdefault(conversation, []).append(message.seq) - displayed = DisplayBasis( - canonical, - basis.registry.require(canonical).incarnation.wire_birth, - tuple( - DisplayedConversation(conversation, tuple(sorted(set(sequences)))) - for conversation, sequences in grouped.items() - ), - RecordedBus(source.identity), - ) - self.reads.mark_displayed(canonical, displayed) - - def channels(self) -> Sequence[str]: - return list(self.channel_declarations()) - def recent_owner_messages( self, thread: Thread, diff --git a/src/agent_comms/messaging/published_bus.py b/src/agent_comms/messaging/published_bus.py index 76859efa41..5ce25f13e3 100644 --- a/src/agent_comms/messaging/published_bus.py +++ b/src/agent_comms/messaging/published_bus.py @@ -29,16 +29,13 @@ def opened_activity(self) -> Iterator[ActivityClocks]: yield self.bus.activity_clocks() -class PublishedBus[Writes](BusResources): - """The live resources; historical clients add their own independent data.""" +class BusCatalog(BusResources): + """The live bus, read ledger, and channel catalog reads independent of publication.""" - @abstractmethod - def __init__[Registry](self, root: Path, registry: Registry, publisher: type[Writes]) -> None: ... + __slots__ = () - publisher: Writes _channels: ChannelCatalog - def require_channel(self, target: str) -> Channel: return self.channel_in(self._channels.read_shared(), target) @@ -51,3 +48,12 @@ def channel_in(self, catalog: CatalogAccess, target: str) -> Channel: def channel_declarations(self): with self.opened_activity() as activity: return self._channels.read_shared().views(activity) + + +class PublishedBus[Writes](BusCatalog): + """The live resources; historical clients add their own independent data.""" + + @abstractmethod + def __init__[Registry](self, root: Path, registry: Registry, publisher: type[Writes]) -> None: ... + + publisher: Writes diff --git a/tests/test_revision_owner_annotations.py b/tests/test_revision_owner_annotations.py index 0b3bc4333c..210a52a7fd 100644 --- a/tests/test_revision_owner_annotations.py +++ b/tests/test_revision_owner_annotations.py @@ -8,6 +8,7 @@ from agent_comms.history_views import HistoryViews from agent_comms.messaging.message_bus import MessageBus +from agent_comms.messaging.bus_reader import BusReader from agent_comms.messaging.published_bus import PublishedBus from agent_comms.planning.goal_management import Goals from agent_comms.planning.goal_presentation import GoalExecutionControls, GoalSnapshot @@ -50,7 +51,8 @@ def test_presentation_sources_are_actual_nominal_providers() -> None: goal_alias = get_type_hints(BusPresentation.__init__)["goals"] goal_source = get_origin(goal_alias) owner, snapshot_contract, registry_contract, activity_contract = get_args(goal_alias) - assert bus_source in MessageBus.__bases__ + assert issubclass(MessageBus, bus_source) + assert bus_source in BusReader.__bases__ assert issubclass(Goals, goal_source) assert goal_source in GoalSnapshotReader.__bases__ assert not isabstract(MessageBus)