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(tests): restore trustworthy backend regression (#1142)

Call White2c9f4b293c46
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index dd5cf379e..a0dd14f93 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -112,7 +112,7 @@ jobs:
uv.lock
- name: Install package and test deps
- run: uv pip install --system -e . pytest jsonschema
+ run: uv pip install --system -e . --group dev
- name: Run unit tests shard ${{ matrix.shard }}/${{ matrix.shard-total }}
run: bash scripts/ci_unit_tests.sh "${{ matrix.shard }}" "${{ matrix.shard-total }}"
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
index 4a19f62bd..09b6a1a95 100644
--- a/core/file_browser_service.py
+++ b/core/file_browser_service.py
@@ -527,6 +527,25 @@ def _mtime_seconds(stat_result: os.stat_result) -> float:
return stat_result.st_mtime_ns / 1_000_000_000
+_MTIME_CONFLICT_TOLERANCE_SECONDS = 1e-6
+_MTIME_TOKEN_STEP_NS = 2_000
+_MTIME_TOKEN_COARSE_STEP_NS = 2_000_000_000
+
+
+def _advance_mtime_token(path: Path, expected_mtime: float) -> None:
+ stat_result = path.stat()
+ if abs(_mtime_seconds(stat_result) - float(expected_mtime)) > _MTIME_CONFLICT_TOLERANCE_SECONDS:
+ return
+ expected_ns = round(float(expected_mtime) * 1_000_000_000)
+ baseline_ns = max(stat_result.st_mtime_ns, expected_ns)
+ for step_ns in (_MTIME_TOKEN_STEP_NS, _MTIME_TOKEN_COARSE_STEP_NS):
+ os.utime(path, ns=(stat_result.st_atime_ns, baseline_ns + step_ns))
+ stat_result = path.stat()
+ if abs(_mtime_seconds(stat_result) - float(expected_mtime)) > _MTIME_CONFLICT_TOLERANCE_SECONDS:
+ return
+ raise OSError("filesystem did not preserve an advanced mtime token")
+
+
def _extension(path: Path) -> str:
suffix = path.suffix
return suffix[1:].lower() if suffix.startswith(".") else suffix.lower()
@@ -718,7 +737,7 @@ def write_file(
current_mtime = _mtime_seconds(target.stat())
except FileNotFoundError as exc:
raise ConflictError("conflict", "File was removed before save") from exc
- if abs(current_mtime - float(expected_mtime)) > 1e-6:
+ if abs(current_mtime - float(expected_mtime)) > _MTIME_CONFLICT_TOLERANCE_SECONDS:
raise ConflictError("conflict", "File changed on disk")
def _write() -> dict[str, Any]:
@@ -772,13 +791,15 @@ def write_file(
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
- if expected_mtime is not None:
- try:
- disk_mtime = _mtime_seconds(target.stat())
- except FileNotFoundError as exc:
- raise ConflictError("conflict", "File was removed before save") from exc
- if abs(disk_mtime - float(expected_mtime)) > 1e-6:
- raise ConflictError("conflict", "File changed on disk")
+ if expected_mtime is not None:
+ try:
+ disk_mtime = _mtime_seconds(target.stat())
+ except FileNotFoundError as exc:
+ raise ConflictError("conflict", "File was removed before save") from exc
+ if abs(disk_mtime - float(expected_mtime)) > _MTIME_CONFLICT_TOLERANCE_SECONDS:
+ raise ConflictError("conflict", "File changed on disk")
+ _advance_mtime_token(Path(temp_name), expected_mtime)
+ os.fsync(handle.fileno())
os.replace(temp_name, target)
temp_name = ""
_fsync_dir(parent)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index e4161538c..ec266d8c3 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -148,7 +148,11 @@ def normalize_agent_run_delivery_intent(value: Any) -> str:
return normalized
-def _path_signature(path: Path) -> Optional[tuple[int, int, int]]:
+_PathSignature = tuple[int, int, int]
+_DirectoryEntrySignature = tuple[tuple[str, Optional[_PathSignature]], ...]
+
+
+def _path_signature(path: Path) -> Optional[_PathSignature]:
try:
stat = path.stat()
except FileNotFoundError:
@@ -156,6 +160,13 @@ def _path_signature(path: Path) -> Optional[tuple[int, int, int]]:
return (stat.st_mtime_ns, stat.st_size, stat.st_ino)
+def _directory_entry_signature(path: Path) -> _DirectoryEntrySignature:
+ return tuple(
+ (entry.name, _path_signature(entry))
+ for entry in sorted(path.glob("*.json"), key=lambda candidate: candidate.name)
+ )
+
+
def _run_file_state_for_status(status: Optional[str]) -> Optional[str]:
if status in {None, ""}:
return None
@@ -1000,7 +1011,7 @@ class ScheduledTaskStore:
def __init__(self, path: Optional[Path] = None):
self.path = path or (paths.get_state_dir() / "scheduled_tasks.json")
self._sqlite = SQLiteBackgroundTaskStore() if path is None else None
- self._signature: Optional[tuple[int, int, int]] = None
+ self._signature: Optional[_PathSignature] = None
self._tasks: Dict[str, ScheduledTask] = {}
#: Set when a failed write left this mirror INCOMPLETE, cleared by the reload
#: that repairs it. See ``maybe_reload`` and ``_reload_after_lost_write``.
@@ -1510,13 +1521,13 @@ class TaskExecutionStore:
self.processing_dir.mkdir(parents=True, exist_ok=True)
self.completed_dir.mkdir(parents=True, exist_ok=True)
- def _state_signature(self) -> tuple[Optional[tuple[int, int, int]], ...] | None:
+ def _state_signature(self) -> tuple[_DirectoryEntrySignature, ...] | None:
if self._sqlite is not None:
return None
return (
- _path_signature(self.pending_dir),
- _path_signature(self.processing_dir),
- _path_signature(self.completed_dir),
+ _directory_entry_signature(self.pending_dir),
+ _directory_entry_signature(self.processing_dir),
+ _directory_entry_signature(self.completed_dir),
)
def maybe_reload(self) -> bool:
diff --git a/docs/plans/test-debt-backend-cleanup.md b/docs/plans/test-debt-backend-cleanup.md
new file mode 100644
index 000000000..bf87d7cd8
--- /dev/null
+++ b/docs/plans/test-debt-backend-cleanup.md
@@ -0,0 +1,98 @@
+# Backend Test-Debt Cleanup Plan
+
+## Evidence and ownership
+
+- The two `tests/test_platform_registry.py` failures are caused by
+ `tests/test_slack_app_mention_empty.py`. Its collection-time loader removes
+ `modules.im.slack` from `sys.modules` and executes the file again under the
+ canonical module name. `PlatformDescriptor.create_client()` then imports the
+ replacement class, while the registry tests retain the original `SlackBot`
+ class object. The test loader owns this mutation and must reuse the canonical
+ module instead of replacing process-global import state.
+- The Show Runtime orphan-sweep failure is not leaked global state. The test
+ calls the sweep immediately after `Popen`; the kernel can expose the child PID
+ before the child completes `exec`, so `psutil` temporarily reports an empty or
+ parent-shaped command line. An Incus stress probe missed 7 of 200 immediate
+ command-line reads. The test helper owns child readiness and will use an
+ explicit stdout-pipe byte from the executed child, with no sleep, polling,
+ platform-specific file-descriptor passing, or production behavior change.
+- The file-backed `TaskExecutionStore` owns its reload token. Directory
+ `(mtime_ns, size, inode)` metadata can remain identical when a JSON entry is
+ added or moved within one ext4 clock tick. The signature will instead be the
+ sorted committed `*.json` entry set for each state directory, including every
+ entry's `(mtime_ns, size, inode)`. This detects names, moves, and the store's
+ atomic replacement writes while ignoring uncommitted `*.tmp` files. The
+ SQLite branch remains unchanged.
+- Pytest currently loads AnyIO but not `pytest-asyncio`: `asyncio_mode` is an
+ unknown option and the five `@pytest.mark.asyncio` integration methods have an
+ unknown marker. They are skipped earlier when credentials are absent, which
+ hides that they cannot execute under their declared runner contract. Add
+ `pytest-asyncio` explicitly to the dev dependency group and lockfile, and run
+ the existing active-event-loop bridge test as a native async test so the
+ ordinary suite enforces `asyncio_mode = "auto"` even without E2E credentials.
+ The sharded unit-test workflow must install the declared dev group rather
+ than maintaining a separate partial test-dependency list.
+- The first post-fix Incus full suite exposed two additional same-tick
+ assumptions. File Browser returns `mtime` as its optimistic-concurrency token,
+ but an atomic replacement can inherit the saved file's token on ext4; the
+ writer owns advancing a successful replacement's token beyond the accepted
+ baseline, verifying the post-`utime` stat, using a coarse-filesystem fallback,
+ and failing before replacement if no distinct token is observable. Contents
+ and the advanced token are one durable publication unit, so the writer also
+ keeps the temp descriptor open and flushes the token mutation before replace;
+ a failed durability flush must leave the original file published.
+ Processed-message retention orders only by `created_at`, while
+ multiple SQLite inserts can receive the same wall-clock value; the SQLite
+ store owns deterministic insertion order and will use the table rowid only as
+ the tie-breaker for equal timestamps. Neither fix needs a sleep, retry, or
+ schema change.
+
+## Invariants
+
+1. Tests never replace a canonical production module in `sys.modules` merely to
+ load the same source again.
+2. A real-process test does not inspect child argv until the child proves that
+ `exec` completed.
+3. Every committed file-backend queue transition changes the observed entry
+ signature even when directory timestamps do not advance.
+4. SQLite task execution behavior and intentional test skips are unchanged.
+5. The configured async pytest mode and marker are provided by an explicit
+ development dependency.
+6. A successful conditional file replacement invalidates its accepted `mtime`
+ token even when the filesystem initially timestamps both versions equally,
+ and durably flushes that token before publishing the replacement.
+7. Equal-timestamp processed-message claims retain and load in SQLite insertion
+ order.
+
+## Acceptance
+
+1. Run the loader-isolation regression before the platform registry tests in one
+ pytest process, then run the reverse order.
+2. Run the Show Runtime orphan-sweep module repeatedly in the lane's Incus
+ target and confirm the real child is immediately discoverable after the
+ readiness handshake.
+3. Run the file-backend reload test with directory signatures forced constant,
+ followed by neighboring scheduled-task store tests.
+4. Run Ruff on every changed Python file and `git diff --check`.
+5. In the isolated Incus target, run the complete backend suite in one process
+ with `VIBE_SHOW_RUNTIME_SOURCE` unset. Record exact pass, skip, fail, and
+ warning counts; confirm `pytest-asyncio` is loaded and the previously failing
+ order is clean.
+6. Force a replacement temp file to the accepted `mtime` and force 205
+ processed-message claims to one timestamp; confirm stale writes still
+ conflict and retention keeps the newest 200 claims in insertion order. Pin
+ the conditional-write order as token `utime`, temp-file `fsync`, then
+ `os.replace`, and prove a failed token flush cannot publish.
+
+## Verification results
+
+- Deterministic red tests reproduced the canonical Slack module replacement,
+ the unchanged directory-stat reload token, a same-`mtime` atomic replacement,
+ a missing durability flush between token advancement and replacement,
+ equal-timestamp SQLite retention, and the missing native async runner.
+- The platform/Slack order passed in both directions (`19 passed` each), and the
+ changed modules plus their neighboring suites passed with `482 passed, 1
+ skipped, 379 warnings`.
+- The isolated Incus full suite ran in one process with `pytest_asyncio.plugin`
+ registered and `VIBE_SHOW_RUNTIME_SOURCE` unset: `7154 passed, 55 skipped,
+ 3904 warnings` in 870.92 seconds, with zero failures.
diff --git a/pyproject.toml b/pyproject.toml
index ffb1be6a0..c13292b4f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -151,4 +151,5 @@ markers = [
dev = [
"jsonschema>=4.26.0",
"pytest>=9.0.3",
+ "pytest-asyncio>=1.4.0",
]
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 885ded4f5..f9409c2bc 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -8,7 +8,7 @@ from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Any, Mapping
-from sqlalchemy import Connection, and_, case, func, or_, select, update
+from sqlalchemy import Connection, and_, case, func, literal_column, or_, select, update
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.exc import IntegrityError
@@ -53,6 +53,9 @@ from storage.session_reclaim import (
from storage.settings_service import make_scope_id, upsert_scope
from storage import message_deliveries as delivery_store
+
+_RUNTIME_RECORD_ROWID = literal_column("runtime_records.rowid")
+
SESSIONS_LAST_ACTIVITY_KEY = "sessions_last_activity"
SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"
@@ -1959,7 +1962,7 @@ class SQLiteSessionsService:
rows = conn.execute(
select(runtime_records.c.payload_json)
.where(runtime_records.c.record_type == "processed_message")
- .order_by(runtime_records.c.created_at)
+ .order_by(runtime_records.c.created_at, _RUNTIME_RECORD_ROWID)
)
result: dict[str, dict[str, list[str]]] = {}
for (payload_json,) in rows:
@@ -2517,7 +2520,7 @@ def _prune_processed_message_records(
select(runtime_records.c.record_key)
.where(runtime_records.c.record_type == "processed_message")
.where(runtime_records.c.record_key.like(prefix_pattern, escape="\\"))
- .order_by(runtime_records.c.created_at.desc())
+ .order_by(runtime_records.c.created_at.desc(), _RUNTIME_RECORD_ROWID.desc())
.offset(200)
).all()
old_record_keys = [row[0] for row in rows]
diff --git a/tests/test_async_bridge.py b/tests/test_async_bridge.py
index 937a76edb..cf0381eb4 100644
--- a/tests/test_async_bridge.py
+++ b/tests/test_async_bridge.py
@@ -1,5 +1,3 @@
-import asyncio
-
import pytest
from vibe.async_bridge import run_coroutine_blocking
@@ -13,9 +11,6 @@ def test_run_coroutine_blocking_allows_sync_callers():
assert run_coroutine_blocking(_value()) == 42
-def test_run_coroutine_blocking_rejects_active_event_loop():
- async def _exercise():
- with pytest.raises(RuntimeError, match="active event loop"):
- run_coroutine_blocking(_value())
-
- asyncio.run(_exercise())
+async def test_run_coroutine_blocking_rejects_active_event_loop():
+ with pytest.raises(RuntimeError, match="active event loop"):
+ run_coroutine_blocking(_value())
diff --git a/tests/test_file_browser_backend.py b/tests/test_file_browser_backend.py
index 9a7ccc165..e40c69e64 100644
--- a/tests/test_file_browser_backend.py
+++ b/tests/test_file_browser_backend.py
@@ -4,6 +4,7 @@ import errno
import io
import logging
import os
+import stat
import sys
import threading
import time
@@ -389,13 +390,43 @@ def test_rename_no_replace_refuses_existing_directory_target(tmp_path, monkeypat
assert dst.is_dir()
-def test_write_is_atomic_and_detects_mtime_conflict(tmp_path):
+def test_write_is_atomic_and_detects_mtime_conflict(tmp_path, monkeypatch):
path = tmp_path / "doc.txt"
first = fs.write_file(str(path), "first")
assert path.read_text(encoding="utf-8") == "first"
- fs.write_file(str(path), "second", expected_mtime=first["mtime"])
+ accepted_mtime_ns = path.stat().st_mtime_ns
+ real_fsync = fs.os.fsync
+ real_utime = fs.os.utime
+ replacement_utimes: list[int] = []
+ regular_fsyncs = 0
+
+ def fsync_at_accepted_mtime(fd: int) -> None:
+ nonlocal regular_fsyncs
+ real_fsync(fd)
+ current = os.fstat(fd)
+ if stat.S_ISREG(current.st_mode):
+ regular_fsyncs += 1
+ if regular_fsyncs == 1:
+ real_utime(fd, ns=(current.st_atime_ns, accepted_mtime_ns))
+
+ def round_first_replacement_utime(target, *, ns):
+ if isinstance(target, int):
+ real_utime(target, ns=ns)
+ return
+ replacement_utimes.append(ns[1])
+ if len(replacement_utimes) == 1:
+ real_utime(target, ns=(ns[0], accepted_mtime_ns))
+ else:
+ real_utime(target, ns=ns)
+
+ monkeypatch.setattr(fs.os, "fsync", fsync_at_accepted_mtime)
+ monkeypatch.setattr(fs.os, "utime", round_first_replacement_utime)
+
+ second = fs.write_file(str(path), "second", expected_mtime=first["mtime"])
assert path.read_text(encoding="utf-8") == "second"
+ assert second["mtime"] != first["mtime"]
+ assert len(replacement_utimes) == 2
with pytest.raises(FileBrowserError) as exc:
fs.write_file(str(path), "stale", expected_mtime=first["mtime"])
@@ -407,6 +438,111 @@ def test_write_is_atomic_and_detects_mtime_conflict(tmp_path):
assert not list(tmp_path.glob(".large.txt.*.tmp"))
+def test_write_fails_before_replace_when_mtime_token_cannot_advance(tmp_path, monkeypatch):
+ path = tmp_path / "doc.txt"
+ first = fs.write_file(str(path), "first")
+ accepted_mtime_ns = path.stat().st_mtime_ns
+ real_fsync = fs.os.fsync
+ real_utime = fs.os.utime
+ regular_fsyncs = 0
+
+ def fsync_at_accepted_mtime(fd: int) -> None:
+ nonlocal regular_fsyncs
+ real_fsync(fd)
+ current = os.fstat(fd)
+ if stat.S_ISREG(current.st_mode):
+ regular_fsyncs += 1
+ if regular_fsyncs == 1:
+ real_utime(fd, ns=(current.st_atime_ns, accepted_mtime_ns))
+
+ def round_replacement_utime(target, *, ns):
+ if isinstance(target, int):
+ real_utime(target, ns=ns)
+ return
+ real_utime(target, ns=(ns[0], accepted_mtime_ns))
+
+ monkeypatch.setattr(fs.os, "fsync", fsync_at_accepted_mtime)
+ monkeypatch.setattr(fs.os, "utime", round_replacement_utime)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.write_file(str(path), "second", expected_mtime=first["mtime"])
+
+ assert exc.value.code == "fs_error"
+ assert path.read_text(encoding="utf-8") == "first"
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+
+def test_conditional_write_syncs_advanced_mtime_before_replace(tmp_path, monkeypatch):
+ path = tmp_path / "doc.txt"
+ path.write_text("first", encoding="utf-8")
+ accepted_mtime = fs._mtime_seconds(path.stat())
+ accepted_mtime_ns = path.stat().st_mtime_ns
+ real_fsync = fs.os.fsync
+ real_utime = fs.os.utime
+ real_replace = fs.os.replace
+ regular_fsyncs = 0
+ events: list[str] = []
+
+ def capture_fsync(fd: int) -> None:
+ nonlocal regular_fsyncs
+ real_fsync(fd)
+ current = os.fstat(fd)
+ if stat.S_ISREG(current.st_mode):
+ regular_fsyncs += 1
+ events.append("fsync")
+ if regular_fsyncs == 1:
+ real_utime(fd, ns=(current.st_atime_ns, accepted_mtime_ns))
+
+ def capture_utime(target, *, ns):
+ events.append("utime")
+ real_utime(target, ns=ns)
+
+ def capture_replace(source, target) -> None:
+ events.append("replace")
+ real_replace(source, target)
+
+ monkeypatch.setattr(fs.os, "fsync", capture_fsync)
+ monkeypatch.setattr(fs.os, "utime", capture_utime)
+ monkeypatch.setattr(fs.os, "replace", capture_replace)
+
+ result = fs.write_file(str(path), "second", expected_mtime=accepted_mtime)
+
+ assert path.read_text(encoding="utf-8") == "second"
+ assert result["mtime"] != accepted_mtime
+ assert events[:4] == ["fsync", "utime", "fsync", "replace"]
+
+
+def test_conditional_write_does_not_publish_when_mtime_fsync_fails(tmp_path, monkeypatch):
+ path = tmp_path / "doc.txt"
+ path.write_text("first", encoding="utf-8")
+ accepted_mtime = fs._mtime_seconds(path.stat())
+ accepted_mtime_ns = path.stat().st_mtime_ns
+ real_fsync = fs.os.fsync
+ real_utime = fs.os.utime
+ regular_fsyncs = 0
+
+ def fail_mtime_fsync(fd: int) -> None:
+ nonlocal regular_fsyncs
+ current = os.fstat(fd)
+ if not stat.S_ISREG(current.st_mode):
+ real_fsync(fd)
+ return
+ regular_fsyncs += 1
+ if regular_fsyncs == 2:
+ raise OSError("mtime fsync failed")
+ real_fsync(fd)
+ real_utime(fd, ns=(current.st_atime_ns, accepted_mtime_ns))
+
+ monkeypatch.setattr(fs.os, "fsync", fail_mtime_fsync)
+
+ with pytest.raises(FileBrowserError) as exc:
+ fs.write_file(str(path), "second", expected_mtime=accepted_mtime)
+
+ assert exc.value.code == "fs_error"
+ assert path.read_text(encoding="utf-8") == "first"
+ assert not list(tmp_path.glob(f"{fs._WRITE_TEMP_PREFIX}*.tmp"))
+
+
def test_write_maps_mkstemp_permission_error(tmp_path, monkeypatch):
path = tmp_path / "doc.txt"
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index cec510b7a..d8c5e0143 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -16,6 +16,7 @@ from sqlalchemy import select, update
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import core.scheduled_tasks as scheduled_tasks
from config import paths
from config.v2_settings import make_thread_native_id
from core.controller import Controller
@@ -1103,8 +1104,17 @@ def test_request_store_enqueue_claim_and_complete(tmp_path: Path) -> None:
assert not (store.processing_dir / f"{request.id}.json").exists()
-def test_request_store_file_backend_reload_detects_queue_changes(tmp_path: Path) -> None:
+def test_request_store_file_backend_reload_detects_queue_changes(tmp_path: Path, monkeypatch) -> None:
root = tmp_path / "task_requests"
+ state_dirs = {root / "pending", root / "processing", root / "completed"}
+ path_signature = scheduled_tasks._path_signature
+
+ def fixed_directory_signature(path: Path):
+ if path in state_dirs:
+ return (1, 1, 1)
+ return path_signature(path)
+
+ monkeypatch.setattr(scheduled_tasks, "_path_signature", fixed_directory_signature)
reader = TaskExecutionStore(root)
writer = TaskExecutionStore(root)
diff --git a/tests/test_show_runtime_orphan_sweep.py b/tests/test_show_runtime_orphan_sweep.py
index ac9807134..b531c0a55 100644
--- a/tests/test_show_runtime_orphan_sweep.py
+++ b/tests/test_show_runtime_orphan_sweep.py
@@ -87,14 +87,21 @@ def _spawn_fake_orphan(workspace_root: str) -> subprocess.Popen:
argv = [
sys.executable,
"-c",
- "import time; time.sleep(120)",
+ "import sys, time; sys.stdout.buffer.write(b'1'); sys.stdout.buffer.flush(); time.sleep(120)",
"cli.js",
"--workspace-root",
workspace_root,
"--fallback-delay-seconds",
"8",
]
- return subprocess.Popen(argv, start_new_session=True)
+ proc = subprocess.Popen(argv, start_new_session=True, stdout=subprocess.PIPE)
+ assert proc.stdout is not None
+ ready = proc.stdout.read(1)
+ proc.stdout.close()
+ if ready != b"1":
+ _reap(proc)
+ raise AssertionError("fake orphan did not reach its executed child process")
+ return proc
def _gone(pid: int, timeout: float = 5.0) -> bool:
diff --git a/tests/test_slack_app_mention_empty.py b/tests/test_slack_app_mention_empty.py
index f8cae6593..d45d4051b 100644
--- a/tests/test_slack_app_mention_empty.py
+++ b/tests/test_slack_app_mention_empty.py
@@ -1,8 +1,7 @@
-import importlib.util
+import importlib
import sys
import types
import unittest
-from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
@@ -89,14 +88,7 @@ def _install_slack_stubs() -> None:
def _load_local_slack_bot():
- repo_root = Path(__file__).resolve().parents[1]
- sys.path.insert(0, str(repo_root))
- sys.modules.pop("modules.im.slack", None)
- spec = importlib.util.spec_from_file_location("modules.im.slack", repo_root / "modules" / "im" / "slack.py")
- assert spec is not None and spec.loader is not None
- module = importlib.util.module_from_spec(spec)
- sys.modules["modules.im.slack"] = module
- spec.loader.exec_module(module)
+ module = importlib.import_module("modules.im.slack")
return module.SlackBot
@@ -113,6 +105,14 @@ class _ResponseLike:
class SlackAppMentionEmptyTests(unittest.IsolatedAsyncioTestCase):
+ def test_loader_preserves_the_canonical_slack_module(self):
+ canonical = sys.modules["modules.im.slack"]
+
+ loaded_class = _load_local_slack_bot()
+
+ self.assertIs(sys.modules["modules.im.slack"], canonical)
+ self.assertIs(loaded_class, canonical.SlackBot)
+
async def test_empty_app_mention_dispatches_empty_message_for_start_menu(self):
slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
received = {}
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index 35d59b9da..d867ca23c 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -3215,10 +3215,15 @@ def test_sessions_store_save_prunes_stale_processed_claim_rows(tmp_path: Path) -
service.close()
-def test_sessions_store_hot_path_prunes_processed_claim_rows(tmp_path: Path) -> None:
+def test_sessions_store_hot_path_prunes_processed_claim_rows(tmp_path: Path, monkeypatch) -> None:
db_path = tmp_path / "vibe.sqlite"
service = SQLiteSessionsService(db_path)
try:
+ monkeypatch.setattr(
+ sessions_service_module,
+ "_utc_now_iso",
+ lambda: "2026-08-03T00:00:00+00:00",
+ )
for index in range(205):
assert service.try_record_processed_message("C123", "171717.123", f"msg-{index:03d}") is True
diff --git a/uv.lock b/uv.lock
index 6585e1826..b01e8665d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -334,6 +334,7 @@ dependencies = [
dev = [
{ name = "jsonschema" },
{ name = "pytest" },
+ { name = "pytest-asyncio" },
]
[package.metadata]
@@ -374,6 +375,16 @@ requires-dist = [
dev = [
{ name = "jsonschema", specifier = ">=4.26.0" },
{ name = "pytest", specifier = ">=9.0.3" },
+ { name = "pytest-asyncio", specifier = ">=1.4.0" },
+]
+
+[[package]]
+name = "backports-asyncio-runner"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8e/ff/70dca7d7cb1cbc0edb2c6cc0c38b65cba36cccc491eca64cabd5fe7f8670/backports_asyncio_runner-1.2.0.tar.gz", hash = "sha256:a5aa7b2b7d8f8bfcaa2b57313f70792df84e32a2a746f585213373f900b42162", size = 69893, upload-time = "2025-07-02T02:27:15.685Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a0/59/76ab57e3fe74484f48a53f8e337171b4a2349e506eabe136d7e01d059086/backports_asyncio_runner-1.2.0-py3-none-any.whl", hash = "sha256:0da0a936a8aeb554eccb426dc55af3ba63bcdc69fa1a600b5bb305413a4477b5", size = 12313, upload-time = "2025-07-02T02:27:14.263Z" },
]
[[package]]
@@ -1764,6 +1775,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" },
]
+[[package]]
+name = "pytest-asyncio"
+version = "1.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "backports-asyncio-runner", marker = "python_full_version < '3.11'" },
+ { name = "pytest" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" },
+]
+
[[package]]
name = "python-dotenv"
version = "1.2.1"