Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
92ec130
feat(core): add sibylnet message and thread tables
hyperb1iss Nov 2, 2026
1f79a1e
feat(api): serve sibylnet channels over /api/net
hyperb1iss Nov 2, 2026
ab855e3
feat(jobs): distill idle sibylnet threads into memory
hyperb1iss Nov 2, 2026
378eea8
feat(cli): add sibyl net post, read and watch
hyperb1iss Nov 2, 2026
227f63a
docs: add the sibylnet guide and teach agents to use it
hyperb1iss Nov 2, 2026
61b6dc3
feat(cli): print the signed-in identity with whoami --json
hyperb1iss Nov 2, 2026
54a9102
fix(net): keep thread distillation inside each author's authority
hyperb1iss Nov 2, 2026
9c153b5
docs(net): describe per-author distillation and pinned projects
hyperb1iss Nov 2, 2026
6dc0dda
fix(net): pin only named threads, and only from explicit projects
hyperb1iss Nov 2, 2026
59c336b
fix(net): keep other agents' control characters out of terminals
hyperb1iss Nov 2, 2026
63a9d95
fix(cli): keep net labels on one line and let whoami use env tokens
hyperb1iss Nov 2, 2026
17e6509
feat(api): look up only the users a page names
hyperb1iss Nov 3, 2026
5f2974e
perf(net): wake waiting watchers from the event bus
hyperb1iss Nov 3, 2026
d0a7bce
fix(net): order the feed on an integer nanosecond key
hyperb1iss Nov 3, 2026
4eb091f
test(net): add the authz matrix, contention and end-to-end suites
hyperb1iss Nov 3, 2026
57a0e44
chore(perf): add the sibylnet scale harness
hyperb1iss Nov 3, 2026
713c271
test(net): run the end-to-end CLI from any directory
hyperb1iss Nov 3, 2026
27a7b3b
test(inventory): count the sibylnet router in the runtime surface
hyperb1iss Nov 5, 2026
60f3f30
perf(net): share woken watchers' reads and never drop a wake
hyperb1iss Nov 5, 2026
bbc6fab
perf(net): index-plan the distillation window on SurrealDB 4.0 too
hyperb1iss Nov 5, 2026
cd12ed3
chore(perf): run sibylnet watchers across worker processes
hyperb1iss Nov 5, 2026
f858e04
test(surreal): check the rollup migration ran, not that it ran last
hyperb1iss Nov 6, 2026
25bbcda
chore(perf): refuse to measure until every replica answers health
hyperb1iss Nov 6, 2026
4e57ece
feat(net): keep every sibylnet message in backups and restores
hyperb1iss Nov 6, 2026
f499b41
docs(net): say channel history is kept forever and backed up
hyperb1iss Nov 6, 2026
59aa29a
fix(net): restore channel history without rewriting or rolling it back
hyperb1iss Nov 6, 2026
09b7ca0
docs(net): say what a merge restore does to channel history
hyperb1iss Nov 6, 2026
2d9e7c1
fix(net): keep channels whole when a restore races posts
hyperb1iss Nov 6, 2026
bb7f9a4
docs(net): say which pin a restore keeps and what a refusal leaves
hyperb1iss Nov 6, 2026
62e6535
merge: bring sibylnet onto the 1.5.0 main
hyperb1iss Nov 24, 2026
26e06b9
test(backup): cover sibylnet rows in the restore conversion check
hyperb1iss Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/api/src/sibyl/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
logs_router,
memory_router,
metrics_router,
net_router,
org_invitations_router,
org_members_router,
orgs_router,
Expand Down Expand Up @@ -323,6 +324,7 @@ async def global_exception_handler(request: Request, exc: Exception) -> JSONResp
app.include_router(memory_router)
app.include_router(metrics_router)
app.include_router(activity_router)
app.include_router(net_router)
app.include_router(settings_router)
app.include_router(synthesis_router)
app.include_router(teams_router)
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/sibyl/api/event_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ class WSEvent(StrEnum):
QUESTION_ANSWERED = "question_answered"
SOURCE_IMPORT_UPDATED = "source_import_updated"
RAW_CAPTURE_CHANGED = "raw_capture_changed"
NET_MESSAGE_POSTED = "net_message_posted"
212 changes: 212 additions & 0 deletions apps/api/src/sibyl/api/net_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
"""Wake long-polling sibylnet readers when a matching message is posted.

A feed reader that found nothing used to re-query the database about once a
second for as long as it waited, so idle watchers cost one query each per
second whether or not anyone posted. Now a post publishes
``net_message_posted`` on the coordination event bus (in-process locally,
Redis pub/sub across pods), every pod's subscriber hands it to this registry,
and only the waiters whose organization, channels and thread match are woken.

A woken waiter re-reads once the new message is out of the feed's settle
window. The wake time is measured from when the event arrived here, which is
after the write committed, so by then the database clock has passed the
message's ``created_at`` plus the window. The bus is fire-and-forget (a
Redis reconnect drops whatever was published meanwhile), so a waiter also
re-reads on a slow safety interval; that interval, not a poll, bounds how
late a message can be after a lost event. Waiters on the same question share
a beat for it, so their re-reads join one shared read (see ``net_reads``),
while different questions spread their beats across the interval.

A waiter registers before its first read. A post that lands between the read
and the wait still wakes it, and a post announced shortly before it
registered, still inside the settle window, is remembered for that window so
the new waiter is woken for it too.
"""

from __future__ import annotations

import asyncio
from collections import deque
from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any

import structlog

from sibyl.api.event_types import WSEvent
from sibyl_core.services.net import SETTLE_SECONDS

log = structlog.get_logger()

# How long after an event a waiter re-reads: the settle window plus a margin
# for the time between the database stamping the row and the event arriving.
WAKE_AFTER_SECONDS = SETTLE_SECONDS + 0.25
# A waiter re-reads at least this often even with no event, which is the most
# a message can be delayed if the bus drops its announcement.
SAFETY_RECHECK_SECONDS = 5.0
# Distinct phases a question's safety beat can take within the interval.
_BEAT_STEPS = 1000


@dataclass(eq=False, slots=True)
class NetWaiter:
"""One long-poll read: what it watches, and when it should read again."""

organization_id: str
channels: frozenset[str] | None
thread: str | None
due: float | None = None
signal: asyncio.Event = field(default_factory=asyncio.Event)

def matches(self, channel: str, thread: str) -> bool:
if self.channels is not None and channel not in self.channels:
return False
return self.thread is None or self.thread == thread

def recheck_in(self, now: float) -> float:
"""Seconds from ``now`` to this waiter's next safety re-read, at most the interval."""
phase = hash((self.organization_id, self.channels, self.thread)) % _BEAT_STEPS
offset = SAFETY_RECHECK_SECONDS * phase / _BEAT_STEPS
return SAFETY_RECHECK_SECONDS - (now - offset) % SAFETY_RECHECK_SECONDS

def wake_at(self, when: float) -> None:
# The earliest pending wake wins: one re-read picks up every message
# that settled by then, and anything later wakes it again.
if self.due is None or when < self.due:
self.due = when
self.signal.set()

async def wait(self, recheck: float, remaining: float) -> None:
"""Return once a matching message has settled, or at the safety recheck.

Waits at most ``recheck`` seconds for a wake. A wake, once it comes,
is slept out to its due time even past the recheck: returning at the
recheck would re-read before the message settled and drop the wake,
leaving the message for the next recheck. Never past ``remaining``,
the request's own time; a message that settles after the request
ends wakes the next request through the recent announcements.
"""
loop = asyncio.get_running_loop()
end = loop.time() + remaining
try:
await asyncio.wait_for(self.signal.wait(), min(recheck, remaining))
except TimeoutError:
return
due = self.due if self.due is not None else loop.time()
self.signal.clear()
self.due = None
delay = min(due, end) - loop.time()
if delay > 0:
await asyncio.sleep(delay)


@dataclass(slots=True)
class _Recent:
channel: str
thread: str
wake_at: float


class NetWakeups:
"""This process's long-poll waiters, by organization."""

def __init__(self) -> None:
self._waiters: dict[str, set[NetWaiter]] = {}
self._recent: dict[str, deque[_Recent]] = {}

@contextmanager
def watch(
self, organization_id: str, channels: frozenset[str] | None, thread: str | None
) -> Generator[NetWaiter]:
"""Register a waiter for the duration of one long-poll read."""
waiter = NetWaiter(organization_id=organization_id, channels=channels, thread=thread)
now = asyncio.get_running_loop().time()
for recent in self._live_recent(organization_id, now):
if waiter.matches(recent.channel, recent.thread):
waiter.wake_at(recent.wake_at)
self._waiters.setdefault(organization_id, set()).add(waiter)
try:
yield waiter
finally:
waiters = self._waiters.get(organization_id)
if waiters is not None:
waiters.discard(waiter)
if not waiters:
del self._waiters[organization_id]

def notify(self, organization_id: str, channel: str, thread: str) -> int:
"""Wake the matching waiters; returns how many were woken."""
now = asyncio.get_running_loop().time()
wake_at = now + WAKE_AFTER_SECONDS
recent = self._recent.setdefault(organization_id, deque())
recent.append(_Recent(channel=channel, thread=thread, wake_at=wake_at))
self._live_recent(organization_id, now)
woken = 0
for waiter in self._waiters.get(organization_id, ()):
if waiter.matches(channel, thread):
waiter.wake_at(wake_at)
woken += 1
return woken

def waiting(self, organization_id: str | None = None) -> int:
if organization_id is not None:
return len(self._waiters.get(organization_id, ()))
return sum(len(waiters) for waiters in self._waiters.values())

def _live_recent(self, organization_id: str, now: float) -> deque[_Recent]:
recent = self._recent.get(organization_id)
if recent is None:
return deque()
while recent and recent[0].wake_at <= now:
recent.popleft()
if not recent:
del self._recent[organization_id]
return recent


net_wakeups = NetWakeups()


async def net_wakeup_subscriber(event: str, data: dict[str, Any], org_id: str | None) -> None:
"""Event-bus subscriber: hand a posted message to this process's waiters."""
if event != WSEvent.NET_MESSAGE_POSTED or org_id is None:
return
channel = data.get("channel")
thread = data.get("thread")
if not isinstance(channel, str) or not isinstance(thread, str):
return
net_wakeups.notify(org_id, channel, thread)


async def announce_net_message(
*, organization_id: str, channel: str, thread: str, message_id: str
) -> None:
"""Publish a stored message on the event bus; never fails the post that stored it."""
from sibyl.api.pubsub import publish_event

try:
await publish_event(
WSEvent.NET_MESSAGE_POSTED,
{
"organization_id": organization_id,
"channel": channel,
"thread": thread,
"message_id": message_id,
},
org_id=organization_id,
)
except Exception as exc:
# Waiters still find the message on their safety recheck.
log.warning("net_message_announce_failed", error=str(exc), organization_id=organization_id)


__all__ = [
"SAFETY_RECHECK_SECONDS",
"WAKE_AFTER_SECONDS",
"NetWaiter",
"NetWakeups",
"announce_net_message",
"net_wakeup_subscriber",
"net_wakeups",
]
152 changes: 152 additions & 0 deletions apps/api/src/sibyl/api/net_reads.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
"""Share one feed read among concurrent sibylnet readers asking the same question.

A post wakes every long-poll waiter on its channel at the same instant, and
each used to read the feed and look up its authors on its own, so one message
cost two queries per waiter, all queued on the same pools at once. Readers in
this process asking the same question (organization, channel set, thread)
now join one read: it starts from the oldest of their cursors, and each
reader keeps the rows after its own cursor, which is the page it would have
read itself at that moment. One author lookup covers every page the read
answered.

A reader only joins a read that has not started, so what it gets was read
after it asked and nothing it was woken for can be missing. While a read is
running, readers that arrive queue for the next one, so a question has at
most one read in flight per process. A reader the shared read cannot answer
exactly, because rows before its cursor filled the read, reads on its own.
"""

from __future__ import annotations

import asyncio
import contextvars
from collections.abc import Awaitable, Callable, Iterable, Mapping
from dataclasses import dataclass, field

from sibyl_core.services.net import NetCursor, NetFeedPage, NetMessageRecord

type FeedQuestion = tuple[str, frozenset[str] | None, str | None]
"""Organization, channels (None for all) and thread (None for any)."""


def _position(cursor: NetCursor) -> tuple[int, str]:
# The feed orders by created_ns, then by uuid as text; so does this.
return (cursor.created_ns, cursor.uuid)


def page_after(shared: NetFeedPage, since: NetCursor, limit: int) -> NetFeedPage | None:
"""The page a read after ``since`` would return, cut from a read that started earlier.

``shared`` holds the settled rows after an earlier or equal cursor, in
feed order, and whether more followed. The rows after ``since`` are a
suffix of it. They answer exactly unless the shared read filled up
before holding ``limit`` of them; then this returns None.
"""
start = _position(since)
after = [message for message in shared.messages if _position(message.cursor) > start]
if shared.more and len(after) < limit:
return None
messages = after[:limit]
return NetFeedPage(
messages=messages,
next_since=messages[-1].cursor if messages else since,
# Rows past the shared read all follow ``since`` too.
more=shared.more or len(after) > limit,
)


@dataclass(eq=False, slots=True)
class _Ask[A]:
since: NetCursor
limit: int
answer: asyncio.Future[tuple[NetFeedPage, Mapping[str, A]] | None]


@dataclass(eq=False, slots=True)
class _Flight[A]:
asks: list[_Ask[A]] = field(default_factory=list)
drain: asyncio.Task[None] | None = None


class SharedFeedReads[A]:
"""This process's feed reads, one in flight per question."""

def __init__(
self,
read_page: Callable[[FeedQuestion, NetCursor, int], Awaitable[NetFeedPage]],
authors: Callable[[Iterable[str]], Awaitable[Mapping[str, A]]],
) -> None:
self._read_page = read_page
self._authors = authors
self._flights: dict[FeedQuestion, _Flight[A]] = {}

async def read(
self, question: FeedQuestion, since: NetCursor, limit: int
) -> tuple[NetFeedPage, Mapping[str, A]]:
"""The page after ``since``, with its authors, read alongside any same-question readers."""
if limit <= 0:
msg = "a shared read needs a positive limit"
raise ValueError(msg)
flight = self._flights.get(question)
if flight is None:
flight = self._flights[question] = _Flight()
ask: _Ask[A] = _Ask(since, limit, asyncio.get_running_loop().create_future())
flight.asks.append(ask)
if flight.drain is None:
# The read serves every reader in the batch, so it runs in no
# one request's context. It starts on the next turn of the loop,
# after every reader woken by the same timer has joined.
flight.drain = asyncio.create_task(
self._drain(question, flight), context=contextvars.Context()
)
answer = await ask.answer
if answer is not None:
return answer
page = await self._read_page(question, since, limit)
return page, await self._authors(_author_ids(page.messages))

def in_flight(self) -> int:
return len(self._flights)

async def _drain(self, question: FeedQuestion, flight: _Flight[A]) -> None:
try:
while flight.asks:
asks = [ask for ask in flight.asks if not ask.answer.done()]
flight.asks = []
if asks:
await self._answer(question, asks)
finally:
for ask in flight.asks:
ask.answer.cancel()
if self._flights.get(question) is flight:
del self._flights[question]

async def _answer(self, question: FeedQuestion, asks: list[_Ask[A]]) -> None:
try:
since = min((ask.since for ask in asks), key=_position)
shared = await self._read_page(question, since, max(ask.limit for ask in asks))
pages = [page_after(shared, ask.since, ask.limit) for ask in asks]
authors = await self._authors(
_author_ids(message for page in pages if page for message in page.messages)
)
except BaseException as exc:
for ask in asks:
if ask.answer.done():
continue
if isinstance(exc, Exception):
ask.answer.set_exception(exc)
else:
ask.answer.cancel()
if not isinstance(exc, Exception):
raise
return
for ask, page in zip(asks, pages, strict=True):
if not ask.answer.done():
ask.answer.set_result(None if page is None else (page, authors))


def _author_ids(messages: Iterable[NetMessageRecord]) -> list[str]:
return list(dict.fromkeys(message.author_user_id for message in messages))


__all__ = ["FeedQuestion", "SharedFeedReads", "page_after"]
3 changes: 3 additions & 0 deletions apps/api/src/sibyl/api/pubsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,12 @@ async def _graph_cache_subscriber(event: str, data: dict[str, Any], org_id: str

async def init_pubsub(local_broadcast_callback: Any) -> None:
"""Initialize the active event bus on server startup."""
from sibyl.api.net_events import net_wakeup_subscriber

bus = get_pubsub()
await bus.connect()
await bus.subscribe(_graph_cache_subscriber)
await bus.subscribe(net_wakeup_subscriber)
await bus.subscribe(local_broadcast_callback)


Expand Down
Loading
Loading