Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(sessions): atomically claim processed messages

cyh7bd0c1b4e774
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index 3424a156e..49c17ae4f 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -385,8 +385,7 @@ class SessionsStore:
"""Check if a message ID is in the processed set."""
return message_ts in self._get_processed_set(channel_id, thread_ts)
- def add_to_processed_set(self, channel_id: str, thread_ts: str, message_ts: str) -> None:
- """Add a message ID to the processed set (bounded)."""
+ def _remember_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> None:
if channel_id not in self.state.processed_message_ts:
self.state.processed_message_ts[channel_id] = {}
value = self.state.processed_message_ts[channel_id].get(thread_ts)
@@ -404,6 +403,19 @@ class SessionsStore:
if len(processed) > self._DEDUP_SET_MAX:
processed = processed[-self._DEDUP_SET_MAX :]
self.state.processed_message_ts[channel_id][thread_ts] = processed
+
+ def try_add_to_processed_set(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:
+ """Atomically add a message ID to the processed set."""
+ self._ensure_service()
+ if not self._service.try_record_processed_message(channel_id, thread_ts, message_ts):
+ self.maybe_reload()
+ return False
+ self._remember_processed_message(channel_id, thread_ts, message_ts)
+ return True
+
+ def add_to_processed_set(self, channel_id: str, thread_ts: str, message_ts: str) -> None:
+ """Add a message ID to the processed set (bounded)."""
+ self._remember_processed_message(channel_id, thread_ts, message_ts)
self.save()
def add_active_poll(self, poll_info: ActivePollInfo) -> None:
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 6e9aa7a20..dab9b19d7 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -79,21 +79,28 @@ class MessageHandler(BaseHandler):
return None
if is_human:
- # Deduplication: check if this message has already been processed
- # This prevents duplicate processing when vibe-remote restarts and
- # Slack resends events
+ # Claim the message before processing so duplicate IM deliveries or
+ # parallel runtime instances cannot start separate agent turns.
message_ts = context.message_id
thread_ts = context.thread_id or context.message_id
if message_ts and thread_ts:
- if self.sessions.is_message_already_processed(context.channel_id, thread_ts, message_ts):
+ try_record = getattr(self.sessions, "try_record_processed_message", None)
+ if callable(try_record):
+ recorded = try_record(context.channel_id, thread_ts, message_ts)
+ else:
+ recorded = not self.sessions.is_message_already_processed(
+ context.channel_id,
+ thread_ts,
+ message_ts,
+ )
+ if recorded:
+ self.sessions.record_processed_message(context.channel_id, thread_ts, message_ts)
+ if not recorded:
logger.info(
f"Skipping already processed message: channel={context.channel_id}, "
f"thread={thread_ts}, message={message_ts}"
)
return None
- # Record this message as processed immediately to prevent duplicates
- # even if processing fails (we don't want to retry failed messages forever)
- self.sessions.record_processed_message(context.channel_id, thread_ts, message_ts)
if is_human and not has_files:
maybe_consume_setup_reply = getattr(self.controller.agent_auth_service, "maybe_consume_setup_reply", None)
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index 6e92bdbdf..3ff7e85b3 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -364,6 +364,17 @@ class SessionsFacade:
self.sessions_store.add_to_processed_set(channel_id, thread_ts, message_ts)
logger.debug("Recorded processed message: channel=%s, thread=%s, message=%s", channel_id, thread_ts, message_ts)
+ def try_record_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:
+ recorded = self.sessions_store.try_add_to_processed_set(channel_id, thread_ts, message_ts)
+ if recorded:
+ logger.debug(
+ "Recorded processed message: channel=%s, thread=%s, message=%s",
+ channel_id,
+ thread_ts,
+ message_ts,
+ )
+ return recorded
+
def add_active_poll(
self,
opencode_session_id: str,
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index c5d8cf8ad..cf425f5b6 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import Any
from sqlalchemy import Connection, select
+from sqlalchemy.exc import IntegrityError
from config.v2_sessions import ActivePollInfo, SessionState
from config.v2_settings import _split_scoped_key
@@ -137,9 +138,51 @@ class SQLiteSessionsService:
last_activity=self._load_last_activity(conn),
)
+ def try_record_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:
+ """Atomically claim a message for processing.
+
+ Multiple Socket Mode clients or stale runtime instances can receive the same
+ IM event. The unique runtime record is the cross-process source of truth.
+ """
+ now = _utc_now_iso()
+ channel_key = str(channel_id)
+ thread_key = str(thread_ts)
+ message_key = str(message_ts)
+ record_key = "|".join((channel_key, thread_key, message_key))
+ try:
+ with self.engine.begin() as conn:
+ conn.execute(
+ runtime_records.insert().values(
+ id=f"runtime::processed_message::{record_key}",
+ record_type="processed_message",
+ record_key=record_key,
+ scope_id=None,
+ session_anchor=thread_key,
+ workdir=None,
+ payload_json=_json_dumps(
+ {
+ "channel_id": channel_key,
+ "thread_id": thread_key,
+ "message_id": message_key,
+ "processed_at": now,
+ }
+ ),
+ expires_at=None,
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ except IntegrityError:
+ return False
+ return True
+
def save_state(self, state: SessionState) -> None:
with self.engine.begin() as conn:
existing_session_ids = self._load_existing_session_ids(conn)
+ state.processed_message_ts = _merge_processed_message_maps(
+ state.processed_message_ts,
+ self._load_processed_messages(conn),
+ )
self._clear(conn)
now = _utc_now_iso()
used_session_ids: set[str] = set(existing_session_ids.values())
@@ -416,6 +459,34 @@ def decode_session_value(value: Any) -> Any:
return value
+def _merge_processed_message_maps(
+ primary: dict[str, dict[str, Any]],
+ secondary: dict[str, dict[str, list[str]]],
+) -> dict[str, dict[str, list[str]]]:
+ result: dict[str, dict[str, list[str]]] = {}
+ seen: set[tuple[str, str, str]] = set()
+ for source in (secondary, primary):
+ if not isinstance(source, dict):
+ continue
+ for channel_id, thread_map in source.items():
+ if not isinstance(thread_map, dict):
+ continue
+ channel_key = str(channel_id)
+ for thread_id, value in thread_map.items():
+ thread_key = str(thread_id)
+ message_ids = [value] if isinstance(value, str) else list(value or [])
+ for message_id in message_ids[-200:]:
+ key = (channel_key, thread_key, str(message_id))
+ if key in seen:
+ continue
+ seen.add(key)
+ result.setdefault(channel_key, {}).setdefault(thread_key, []).append(str(message_id))
+ for thread_map in result.values():
+ for thread_id, message_ids in list(thread_map.items()):
+ thread_map[thread_id] = message_ids[-200:]
+ return result
+
+
def _legacy_scope_key(row: dict[str, Any]) -> str:
metadata = _json_loads(row.get("metadata_json"), {})
if isinstance(metadata, dict) and metadata.get("legacy_scope_key"):
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index 8e934b950..dfa85fc5f 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -240,6 +240,48 @@ def test_sessions_store_lifecycle_survives_followup_save(tmp_path: Path) -> None
reloaded.close()
+def test_sessions_store_atomically_claims_processed_messages_across_instances(tmp_path: Path) -> None:
+ sessions_path = tmp_path / "sessions.json"
+ first = SessionsStore(sessions_path)
+ second = SessionsStore(sessions_path)
+ try:
+ assert first.try_add_to_processed_set("C123", "171717.123", "171717.456") is True
+ assert second.try_add_to_processed_set("C123", "171717.123", "171717.456") is False
+ assert second.is_message_in_processed_set("C123", "171717.123", "171717.456") is True
+ finally:
+ first.close()
+ second.close()
+
+
+def test_sessions_store_save_preserves_external_processed_claims(tmp_path: Path) -> None:
+ sessions_path = tmp_path / "sessions.json"
+ stale = SessionsStore(sessions_path)
+ external = SessionsStore(sessions_path)
+ try:
+ assert external.try_add_to_processed_set("C123", "171717.123", "171717.456") is True
+
+ stale.add_active_poll(
+ ActivePollInfo(
+ opencode_session_id="oc-stale",
+ base_session_id="base",
+ channel_id="C123",
+ thread_id="171717.123",
+ settings_key="C123",
+ working_path="/repo",
+ platform="slack",
+ )
+ )
+
+ reloaded = SessionsStore(sessions_path)
+ try:
+ assert reloaded.is_message_in_processed_set("C123", "171717.123", "171717.456") is True
+ finally:
+ reloaded.close()
+ finally:
+ stale.close()
+ external.close()
+
+
def test_sessions_store_bootstrap_uses_config_primary_platform(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
paths.ensure_data_dirs()