[Bug]: cascade retry budget is forgotten by a restart during the inline backoff; a row can retry forever without becoming failed

Aperta
#549 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@feiiiiii5 ci sta già lavorando.

Dal 1/11/2026.

  • #553 di @feiiiiii5 — aperta

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
56/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python, sqlite
Ambito
backend, databases

Direzione di ricerca

Read src/everos/memory/cascade/worker.py around _process_one and src/everos/infra/persistence/sqlite/repos/md_change_state.py around recover_orphan_processing. Run the supplied restart replay test with its _harness.py to confirm the retry count resets during backoff cancellation. Done means attempts remain bounded across restarts and the row eventually becomes failed so cascade fix can list it.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug
Area

src/everos

What happened?

_process_one counts its inline attempts in memory and persists retry_count only in the final mark_failed (src/everos/memory/cascade/worker.py:838-876). A process that dies during one of the backoff sleeps (2 s / 4 s / 6 s with the defaults) leaves the row processing with the old retry_count; the restart's recover_orphan_processing resets it to pending without touching retry_count (md_change_state.py:374-390), and the next drain starts the ladder at attempt 0 again. With restarts recurring while an external service is down, the row never reaches failed: _MAX_TOTAL_RETRIES (12) never bounds the attempts, cascade fix never lists the file, and every restart re-runs the handler (an embedding call per attempt) on the same row. Item 6 of #542, now replayed.

Expected: the retry budget counts every attempt made, across restarts.

Scope: needs a restart to land inside the ladder (≤ 12 s per cycle with the defaults) repeatedly; a deploy loop or a supervisor restarting on the failure that causes the retries does exactly that. Low severity on its own; listed because the budget is the only thing that turns a permanently failing file into something cascade fix shows.

Steps to reproduce

Real scanner / worker / EpisodeHandler / repositories; the embedder raises EmbeddingServiceError on every call; max_retry=3, backoff 0.5 s. The process death is simulated by cancelling the drain task during the backoff sleep (as in the #540 replay); the SQLite row looks the same either way.

  1. Five times: drain_once() started, attempt 0 fails, the task is cancelled in the backoff sleep → row processing; recover_orphan_processing() → status=pending, persisted retry_count=0. After five restarts: 5 handler attempts made, retry_count still 0, nothing for cascade fix.
  2. Control, no restarts: permanently failed after 4 uninterrupted drain cycles, retry_count=12 (3 inline attempts per cycle, the scanner's auto-retry carries retry_count across cycles).
replay test (~15 s, real scanner / worker / EpisodeHandler / SQLite / LanceDB; put both files in one directory and run uv run pytest <test file> -q -s)

test_replay_6_restart_resets_retry_budget.py:

"""Replay of #542 item 6: a restart inside the inline retry ladder resets the retry
budget.

``_process_one`` counts inline attempts in memory and only the final ``mark_failed``
persists ``retry_count`` (worker.py:838-876). A process that dies during the
backoff sleep leaves the row ``processing`` with the old ``retry_count``; the
restart's ``recover_orphan_processing`` resets it to ``pending`` without touching
``retry_count``, and the next drain starts the ladder from attempt 0 again. With
restarts recurring, the row never reaches ``failed``, so ``_MAX_TOTAL_RETRIES`` (12)
never bounds the attempts and ``cascade fix`` never lists the file. Control: with
no restarts the budget is spent in 4 drain cycles.

The process death is simulated by cancelling the drain task during the backoff
sleep, the same way the OME replay (#540) simulated it; the SQLite row looks the
same either way.

Run: uv run pytest .work_context/replay_542/test_replay_6_restart_resets_retry_budget.py -q -s
"""

from __future__ import annotations

import asyncio
import contextlib
from typing import Any

from _harness import DIM, Harness
from everos.component.embedding import EmbeddingProvider
from everos.core.errors import EmbeddingServiceError

M = 1_700_000_000.0


class _Embedder(EmbeddingProvider):
    """The embedding service is down for good: every call fails (recoverable class)."""

    dim = DIM

    def __init__(self) -> None:
        self.calls = 0

    async def embed(self, text: str) -> list[float]:
        self.calls += 1
        raise EmbeddingServiceError("embedding 503")

    async def embed_batch(self, texts: Any) -> list[list[float]]:
        return [await self.embed(t) for t in texts]


async def _replay() -> None:
    emb = _Embedder()
    h = await Harness().open(emb)
    try:
        # 3 inline attempts with 0.5 s backoff between them (defaults are 2 s / 4 s / 6 s)
        worker = h.worker(max_retry=3, retry_backoff_seconds=0.5)
        await h.write("u1", 1, "content", M)
        await h.scanner.scan_once()

        for i in range(1, 6):
            task = asyncio.create_task(worker.drain_once())
            await asyncio.sleep(0.25)  # attempt 0 failed, worker sleeps in the backoff
            task.cancel()  # the process dies here
            with contextlib.suppress(asyncio.CancelledError):
                await task
            r = await h.row("u1")
            assert r.status == "processing"
            n = await h.state_repo.recover_orphan_processing()  # the restart
            r = await h.row("u1")
            print(
                f"  restart {i}: recovered {n} row, status={r.status}, persisted retry_count={r.retry_count}, handler attempts so far={emb.calls}"
            )
            assert r.status == "pending" and r.retry_count == 0
        print(
            f"  five restarts: {emb.calls} attempts made, the row is still pending with retry_count 0; cascade fix would list nothing"
        )

        # control: no restarts -> the budget is spent and the row becomes permanently failed
        cycles = 0
        while True:
            await worker.drain_once()
            cycles += 1
            r = await h.row("u1")
            if r.status == "failed" and r.retryable is False:
                break
            assert cycles < 20, (r.status, r.retryable, r.retry_count)
            await (
                h.scanner.scan_once()
            )  # scanner auto-retry keeps retry_count (failed + mtime unchanged)
        print(
            f"  control: permanently failed after {cycles} uninterrupted drain cycles, retry_count={r.retry_count}"
        )
        assert r.retry_count == 12 and cycles == 4
    finally:
        await h.close()


def test_restart_during_backoff_forgets_the_attempts() -> None:
    asyncio.run(_replay())

_harness.py:

"""Shared harness for the #542 replays: real scanner / worker / EpisodeHandler on a
temp memory root, real ``md_change_state`` repository (temp SQLite), real LanceDB
table; the embedder is injected per replay, the tokenizer is a stand-in."""

from __future__ import annotations

import datetime as dt
import shutil
import tempfile
from pathlib import Path
from typing import Any
from unittest import mock

from sqlmodel import SQLModel

import everos.component.embedding.accessor as acc
from everos.component.embedding import EmbeddingCapability, EmbeddingProvider
from everos.component.tokenizer import Tokenizer
from everos.config import LanceDBSettings, SqliteSettings
from everos.core.persistence import (
    MemoryRoot,
    create_session_factory,
    create_system_engine,
)
from everos.core.persistence.lancedb import LanceRepoBase, open_lancedb_connection
from everos.infra.persistence.index import Episode
from everos.infra.persistence.lancedb.repos.episode import _EpisodeRepo
from everos.infra.persistence.markdown import EpisodeWriter
from everos.infra.persistence.predicate import eq
from everos.infra.persistence.sqlite.repos.md_change_state import _MdChangeStateRepo
from everos.memory.cascade import scanner as scanner_mod
from everos.memory.cascade import worker as worker_mod
from everos.memory.cascade.handlers import HandlerDeps
from everos.memory.cascade.handlers.episode import EpisodeHandler
from everos.memory.cascade.scanner import CascadeScanner
from everos.memory.cascade.worker import CascadeWorker

DATE = dt.date(2026, 5, 14)
DIM = 1024


class _Tokenizer(Tokenizer):
    def tokenize(self, text: str) -> list[str]:
        return [t for t in text.split() if t]

    def tokenize_batch(self, texts: Any) -> list[list[str]]:
        return [self.tokenize(t) for t in texts]


def entry(owner: str, n: int, content: str) -> tuple[dict[str, Any], dict[str, Any]]:
    return (
        {
            "owner_id": owner,
            "session_id": "s1",
            "timestamp": "2026-05-14T10:00:00+00:00",
            "parent_type": "memcell",
            "parent_id": f"mc_{n}",
            "sender_ids": [owner],
        },
        {"Subject": "T", "Summary": "S", "Content": content},
    )


def rel(owner: str) -> str:
    return f"default_app/default_project/users/{owner}/episodes/episode-{DATE.isoformat()}.md"


class Harness:
    def __init__(self) -> None:
        self.tmp = Path(tempfile.mkdtemp(prefix="replay542_"))
        self.root = MemoryRoot(self.tmp / "root")
        self.root.ensure()
        self.engine = create_system_engine(self.root.system_db, SqliteSettings())
        self.factory = create_session_factory(self.engine)
        self.state_repo = _MdChangeStateRepo(session_factory=self.factory)
        self.index: Any = None
        self.patches: list[Any] = []
        self.writer = EpisodeWriter(self.root)
        self.scanner = CascadeScanner(self.root, scan_interval_seconds=3600.0)

    async def open(self, embedder: EmbeddingProvider) -> Harness:
        async with self.engine.begin() as conn:
            await conn.run_sync(SQLModel.metadata.create_all)
        LanceRepoBase._reset_locks_for_tests()
        conn = await open_lancedb_connection(self.root.lancedb_dir, LanceDBSettings())
        table = await conn.create_table(Episode.TABLE_NAME, schema=Episode)
        self.index = _EpisodeRepo(table=table)
        acc._capability = EmbeddingCapability(provider=embedder)
        self.patches = [
            mock.patch.object(scanner_mod, "md_change_state_repo", self.state_repo),
            mock.patch.object(scanner_mod, "get_session_factory", lambda: self.factory),
            mock.patch.object(worker_mod, "md_change_state_repo", self.state_repo),
            mock.patch.object(EpisodeHandler, "index_repo", self.index),
        ]
        for p in self.patches:
            p.start()
        return self

    def handler(self) -> EpisodeHandler:
        return EpisodeHandler(
            HandlerDeps(memory_root=self.root, tokenizer=_Tokenizer())
        )

    def worker(self, **overrides: Any) -> CascadeWorker:
        kw: dict[str, Any] = dict(
            batch_size=10,
            handler_concurrency=2,
            max_retry=0,
            retry_backoff_seconds=0.0,
            poll_interval_seconds=3600.0,
            optimize_min_interval_seconds=0.0,
            optimize_heartbeat_seconds=3600.0,
            optimize_rebuild_interval_seconds=3600.0,
        )
        kw.update(overrides)
        return CascadeWorker({"episode": self.handler()}, **kw)

    async def write(self, owner: str, n: int, content: str, mtime: float) -> Path:
        await self.writer.append_entries(owner, [entry(owner, n, content)], date=DATE)
        path = self.root.root / rel(owner)
        import os

        os.utime(path, (mtime, mtime))
        return path

    async def row(self, owner: str) -> Any:
        return next(
            (r for r in await self.state_repo.list_all() if r.md_path == rel(owner)),
            None,
        )

    async def counts(self) -> dict[str, int]:
        out: dict[str, int] = {}
        for r in await self.state_repo.list_all():
            out[r.status] = out.get(r.status, 0) + 1
        return out

    async def indexed(self, owner: str) -> int:
        return len(await self.index.find_where(eq("md_path", rel(owner))))

    async def close(self) -> None:
        for p in self.patches:
            p.stop()
        await self.engine.dispose()
        shutil.rmtree(self.tmp, ignore_errors=True)
Relation to other issues

#542 item 6.

Environment
OS: macOS 15 (Darwin 24.6.0)
Python: 3.12
Commit: 5b0979b (v1.5.1)
Possible fixes (not decided)
  1. Persist the attempt before sleeping: bump retry_count on the row at each inline failure (one small UPDATE), so a restart resumes the budget where it stopped.
  2. Or count attempts at claim time (claim_pending_batch increments a column), which also bounds a row that keeps being reclaimed by restarts for any other reason.
Lingua principale
Python
Stelle
13.3k
Fork
926
Merge medio
23h 31m
PR unite (30g)
26

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di EverMind-AI/EverOS

Tutte le issue di EverMind-AI/EverOS

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.