HEL-882 rework: execution-table caps become real hard gates at the wire, SDK hidden retries and mid-add failures recover without loss, the 8360 release package runs offline, and the HEL-874 embedding evidence is corrected - every real provider exit (create/dialogue/life/gist/judgment/growth/proactive phrasing + mem0's internal extraction LLM) now persistently pre-allocates request count (per-category daily + one-shot totals in request_usage/budget_total, BEGIN IMMEDIATE) and a conservative token estimate before sending, refuses at the tightest cap (BudgetStop, no more downgrade-and-keep-calling) and survives restarts; known usage settles to actual, unknown/disconnect/failure keeps the full reservation; ledger guards gain per-day tops (embed_daily/llm_daily) and verify_ledger_authority rejects a fresh file bypassing the frozen 498/500 prefix; the mem0 SDK client's hidden OpenAI retries are disabled (max_retries=0) so every actual send is gated and answered failures (even 5xx) settle as used with only httpx.ConnectError-grade unsent requests released; embed refusals the SDK swallows into empty adds are re-raised as budget errors so the batch re-queues without burning an attempt and resumes when the cap returns, add_group resumes at vector-store level (src_group anchors: only missing rows resent, crash/restart/concurrency never duplicate), sem coverage is per-backend (stub batches no longer block a real rebuild, real done batches never resend) with backend-scoped batch keys; the release package is offline-executable: fresh-dir git clone, cybergril service account, PYTHONPATH in the unit so the lock-only venv imports the product, shipped caps explicitly 0 (=refuse by design until approved), deploy/mem0-stack.lock + accurate 3.11 wheel gap with a no-download path (hel857-venv is 3.10; never present stub/FTS as the real memory experience), and tools/check_release_offline_hel882.py verifies checkout/import/health/fail-closed/approved-run/data-preservation on loopback with echo stand-ins; evidence corrected per manager review: docs/rework/hel874/erratum-hel882.json + README appendix record that e978e87's verification did real local embeddings from cache (provable lower bound 12, exact total unrecoverable, temp sandbox gone) while zero-real-LLM/zero-download/zero-outbound stand, old JSONs and authoritative ledgers untouched, and tools/verify_mem0_real_hel874.py now installs the deterministic 512-dim stand-in before TextEmbedding construction plus non-loopback socket rejection (zero model loads) with final_embed_rows persisted before temp cleanup; verification: 272 python tests pass on 3.11.16 venv + requirements.lock offline (16 new: manager api repro blocked with 0 provider calls, sdk repro 1-HTTP/max_retries=0/llm_ops=1, mid-add swallow requeued-then-resumed, resume-no-duplicate, stub-to-mem0 rebuild, daily embed cap, unified mem0-LLM gate, authority refusal, restart-persistent counters, tightest-constraint settle/release), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned-install deterministic re-run 12/12, manager review scripts re-run evidence attached in delivery, dual-target requirement checks 4/4 with handoff-HEL-882.json; zero real calls, zero real embeddings, zero non-loopback outbound, authoritative ledgers and freezes untouched, not deployed, PR not merged, no visual changes
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
co-authored by
multica-agent
parent
e978e878df
commit
e291058754
@@ -9,6 +9,30 @@ import pytest
|
||||
from cybergril.config import CharacterConfig, ModelsConfig, Settings
|
||||
from cybergril.memory import Store
|
||||
|
||||
try:
|
||||
from cybergril.think.budget import CATEGORIES, BudgetConfig
|
||||
except ImportError: # r3 baseline probe runs these tests against older src trees
|
||||
from cybergril.think.budget import BudgetConfig
|
||||
|
||||
CATEGORIES = ("dialogue", "life", "background", "semantic")
|
||||
|
||||
|
||||
def engineering_budget(**overrides) -> BudgetConfig:
|
||||
"""Engineering caps for isolated tests: real mechanism, generous numbers.
|
||||
|
||||
The product default is fail-closed (all request caps 0 = refuse); tests
|
||||
exercise the same acquire/settle path with plenty of headroom so the gate
|
||||
itself is what's under test, not the headroom. Against a pre-HEL-882
|
||||
baseline source tree (r3 baseline probe) the extra fields don't exist and
|
||||
the old plain token config is used — behavior there predates the gate.
|
||||
"""
|
||||
requests = dict.fromkeys(CATEGORIES, 100_000)
|
||||
requests.update(overrides.pop("daily_requests", {}))
|
||||
try:
|
||||
return BudgetConfig(daily_tokens=10_000_000, daily_requests=requests, **overrides)
|
||||
except TypeError:
|
||||
return BudgetConfig(daily_tokens=10_000_000, **overrides)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo_root() -> Path:
|
||||
|
||||
+3
-1
@@ -12,6 +12,7 @@ from uuid import uuid4
|
||||
import httpx
|
||||
import pytest
|
||||
import uvicorn
|
||||
from conftest import engineering_budget
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from cybergril.api.app import create_app
|
||||
@@ -56,7 +57,8 @@ class ControlledLLM(EchoLLM):
|
||||
def make_app(path, provider=None, **kwargs):
|
||||
provider = provider or ControlledLLM()
|
||||
router = build_router(
|
||||
providers={Tier.HIGH: provider, Tier.STANDARD: provider, Tier.LOW: provider}
|
||||
providers={Tier.HIGH: provider, Tier.STANDARD: provider, Tier.LOW: provider},
|
||||
budget=engineering_budget(),
|
||||
)
|
||||
return create_app(db_path=path, router=router, **kwargs), provider
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""HEL-882 hard gates: the execution table's caps stop calls at the wire.
|
||||
|
||||
Reproduces the manager's independent review failure first (api review:
|
||||
daily_tokens=1 with 2962 already used still fired a provider request and
|
||||
returned chat.final), then proves the gate: every real provider exit — main
|
||||
dialogue, structured background scenes, and the mem0 SDK's internal extraction
|
||||
LLM — pre-allocates persistently before the send and refuses at the tightest
|
||||
cap with ZERO provider calls. Counters survive restarts.
|
||||
"""
|
||||
import pytest
|
||||
from conftest import engineering_budget
|
||||
from fastapi.testclient import TestClient
|
||||
from test_api import CREATE, events, turn
|
||||
|
||||
from cybergril.api.app import create_app
|
||||
from cybergril.contracts import LLMDelta
|
||||
from cybergril.life.runtime import LifeConfig
|
||||
from cybergril.memory.store import Store
|
||||
from cybergril.think.budget import BudgetConfig, BudgetGuard, BudgetStop
|
||||
from cybergril.think.router import build_router
|
||||
from cybergril.think.scenes import Scene, Tier
|
||||
|
||||
|
||||
class GateLLM:
|
||||
"""Fake provider that records every stream call."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
async def stream(self, messages, **kwargs):
|
||||
self.calls.append(messages)
|
||||
if messages and "只返回JSON" in messages[0].content:
|
||||
yield LLMDelta(text='{"ok": true}')
|
||||
yield LLMDelta(done=True, finish_reason="stop", usage={"total_tokens": 12})
|
||||
return
|
||||
yield LLMDelta(text="好")
|
||||
yield LLMDelta(text="的")
|
||||
yield LLMDelta(done=True, finish_reason="stop", usage={"total_tokens": 12})
|
||||
|
||||
async def aclose(self):
|
||||
return None
|
||||
|
||||
|
||||
def gated_app(tmp_path, *, budget=None, db="gates.db"):
|
||||
provider = GateLLM()
|
||||
router = build_router(
|
||||
providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)},
|
||||
budget=budget or engineering_budget(),
|
||||
)
|
||||
app = create_app(db_path=tmp_path / db, router=router,
|
||||
life_config=LifeConfig(enabled=True, poll_seconds=3600),
|
||||
semantic_mode="off")
|
||||
return app, provider
|
||||
|
||||
|
||||
def create_companion(client):
|
||||
assert client.post("/api/companion", json=CREATE).status_code == 201
|
||||
|
||||
|
||||
def test_daily_token_wall_refuses_before_any_provider_call(tmp_path):
|
||||
"""The review's exact reproduction: over the daily token top, a turn must
|
||||
not reach the provider — honest chat.error, counters unchanged."""
|
||||
app, provider = gated_app(tmp_path)
|
||||
with TestClient(app) as client:
|
||||
create_companion(client)
|
||||
guard = app.state.life.router.guard
|
||||
guard.config.daily_tokens = 1
|
||||
guard.record(2962, "review_budget_already_used")
|
||||
used_before, calls_before = guard.used, len(provider.calls)
|
||||
result = [e["t"] for e in events(turn(client, "合成测试:额度用完后仍能发出请求吗"))]
|
||||
assert result == ["chat.error"] # honest refusal, never a fake reply
|
||||
assert len(provider.calls) == calls_before # ZERO provider requests
|
||||
assert guard.used == used_before # nothing further pre-allocated
|
||||
|
||||
|
||||
def test_dialogue_request_cap_persists_across_restart(tmp_path):
|
||||
"""Category daily request caps are persistent: 1 dialogue request/day lets
|
||||
exactly one turn through; a second turn — in the SAME process or after a
|
||||
full restart on the same database — refuses with zero provider calls."""
|
||||
budget = engineering_budget(daily_requests={"dialogue": 1})
|
||||
app, provider = gated_app(tmp_path, budget=budget)
|
||||
with TestClient(app) as client:
|
||||
create_companion(client)
|
||||
assert [e["t"] for e in events(turn(client, "第一句"))][-1] == "chat.final"
|
||||
calls_after_first = len(provider.calls)
|
||||
assert [e["t"] for e in events(turn(client, "第二句"))] == ["chat.error"]
|
||||
assert len(provider.calls) == calls_after_first
|
||||
|
||||
# restart: fresh app, fresh router, SAME database — the cap still holds
|
||||
app2, _provider2 = gated_app(tmp_path, budget=budget)
|
||||
with TestClient(app2) as client:
|
||||
assert [e["t"] for e in events(turn(client, "重启后"))] == ["chat.error"]
|
||||
assert app2.state.life.router.guard.requests_used("dialogue") == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_background_category_caps_stop_structured_calls(tmp_path):
|
||||
"""structured() exits (life events, gists, judgments) count into their own
|
||||
category: a 1/day life cap refuses the second generation before the wire."""
|
||||
app, provider = gated_app(tmp_path, budget=engineering_budget(
|
||||
daily_requests={"dialogue": 100, "life": 1, "background": 100}))
|
||||
with TestClient(app) as client:
|
||||
create_companion(client)
|
||||
guard = app.state.life.router.guard
|
||||
assert guard.requests_used("background") >= 0 # persistent guard wired
|
||||
calls_before = len(provider.calls)
|
||||
|
||||
from cybergril.life.model import structured
|
||||
|
||||
scene = Scene.LIFE_EVENT
|
||||
payload = {"time": "2026-10-26T10:00:00", "persona": "p", "activity_state": {}}
|
||||
raw, _ = await structured(app.state.life.router, app.state.life.models, scene,
|
||||
'返回 {"ok": true}', payload)
|
||||
assert raw == {"ok": True}
|
||||
assert len(provider.calls) == calls_before + 1
|
||||
with pytest.raises(BudgetStop, match="budget_requests_exhausted:life"):
|
||||
await structured(app.state.life.router, app.state.life.models, scene,
|
||||
'返回 {"ok": true}', payload)
|
||||
assert len(provider.calls) == calls_before + 1 # refused before the wire
|
||||
|
||||
|
||||
def test_default_config_is_fail_closed_for_every_category():
|
||||
guard = BudgetGuard(BudgetConfig())
|
||||
for scene in ("dialogue_main", "life_event", "memory_gist", "mem0_extract"):
|
||||
with pytest.raises(BudgetStop):
|
||||
guard.acquire(scene, requests=1, tokens=10)
|
||||
|
||||
|
||||
def test_in_memory_guard_tightest_constraint_and_settlement():
|
||||
guard = BudgetGuard(BudgetConfig(daily_tokens=1000, daily_requests={"dialogue": 2},
|
||||
total_requests=3), today="2026-10-26")
|
||||
hold1 = guard.acquire("dialogue_main", requests=1, tokens=300)
|
||||
assert guard.requests_used("dialogue") == 1
|
||||
# daily token wall: the tightest cap decides, not the request count
|
||||
with pytest.raises(BudgetStop, match="budget_tokens_exhausted"):
|
||||
guard.acquire("dialogue_main", requests=1, tokens=800)
|
||||
hold2 = guard.acquire("dialogue_main", requests=1, tokens=100)
|
||||
# category daily top reached
|
||||
with pytest.raises(BudgetStop, match="budget_requests_exhausted:dialogue"):
|
||||
guard.acquire("proactive_message", requests=1, tokens=10)
|
||||
# one-shot total: third request would pass the daily top of 2? no — category
|
||||
# top already 2/2; use another category for the total check
|
||||
guard3 = BudgetGuard(BudgetConfig(daily_tokens=1000, daily_requests={"dialogue": 10},
|
||||
total_requests=2), today="2026-10-26")
|
||||
guard3.acquire("dialogue_main", requests=1, tokens=10)
|
||||
guard3.acquire("dialogue_main", requests=1, tokens=10)
|
||||
with pytest.raises(BudgetStop, match="budget_total_requests_exhausted"):
|
||||
guard3.acquire("dialogue_main", requests=1, tokens=10)
|
||||
# settle: known usage adjusts, unknown keeps the whole reservation
|
||||
guard.settle(hold1, actual_tokens=250)
|
||||
assert guard.used == 350 # 250 + hold2's 100
|
||||
guard.settle(hold2, actual_tokens=None) # disconnect: keep full reserve
|
||||
assert guard.used == 350
|
||||
# release: a provably-unsent hold refunds requests and tokens
|
||||
guard4 = BudgetGuard(BudgetConfig(daily_tokens=1000,
|
||||
daily_requests={"dialogue": 1}), today="2026-10-26")
|
||||
hold = guard4.acquire("dialogue_main", requests=1, tokens=100)
|
||||
guard4.release(hold)
|
||||
assert guard4.used == 0 and guard4.requests_used("dialogue") == 0
|
||||
|
||||
|
||||
def test_persistent_budget_counters_survive_restart(tmp_path):
|
||||
from cybergril.life.model import PersistentBudget
|
||||
|
||||
store = Store(tmp_path / "persist.db")
|
||||
guard = PersistentBudget(store, BudgetGuard(engineering_budget(), today="2026-10-26"))
|
||||
guard.acquire("dialogue_main", requests=1, tokens=111)
|
||||
guard.acquire("mem0_extract", requests=2, tokens=22)
|
||||
store.close()
|
||||
|
||||
store2 = Store(tmp_path / "persist.db")
|
||||
guard2 = PersistentBudget(store2, BudgetGuard(engineering_budget(), today="2026-10-26"))
|
||||
assert guard2.requests_used("dialogue") == 1
|
||||
assert guard2.requests_used("semantic") == 2
|
||||
assert guard2.used == 133 # restart did not reset the day's tokens
|
||||
store2.close()
|
||||
|
||||
|
||||
def test_total_tokens_cap_blocks_before_daily_wall(tmp_path):
|
||||
app, provider = gated_app(tmp_path, budget=engineering_budget(
|
||||
daily_requests={"dialogue": 100}, total_tokens=5000))
|
||||
with TestClient(app) as client:
|
||||
create_companion(client)
|
||||
guard = app.state.life.router.guard
|
||||
guard.record(4999, "review_almost_total") # one-shot total nearly spent
|
||||
calls_before = len(provider.calls)
|
||||
assert [e["t"] for e in events(turn(client, "还会发吗"))] == ["chat.error"]
|
||||
assert len(provider.calls) == calls_before
|
||||
@@ -14,6 +14,7 @@ import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import types
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -39,6 +40,22 @@ class FakeQdrantClient:
|
||||
bucket = POINT_LOG.setdefault(collection_name, {})
|
||||
return [_Point(i, bucket[i]) for i in ids if i in bucket]
|
||||
|
||||
def scroll(self, collection_name, scroll_filter=None, limit=10, offset=None,
|
||||
with_payload=True):
|
||||
"""Mirror qdrant scroll-by-payload-filter: must== match on src_group."""
|
||||
bucket = POINT_LOG.setdefault(collection_name, {})
|
||||
must = getattr(scroll_filter, "must", None) or []
|
||||
wanted = None
|
||||
for condition in must:
|
||||
match = getattr(condition, "match", None)
|
||||
if getattr(condition, "key", None) == "src_group" and match is not None:
|
||||
wanted = getattr(match, "value", None)
|
||||
points = [
|
||||
_Point(point_id, payload) for point_id, payload in bucket.items()
|
||||
if wanted is None or payload.get("src_group") == wanted
|
||||
]
|
||||
return points[:limit], None
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
@@ -58,11 +75,19 @@ class FakeEmbedder:
|
||||
return [[0.0]] * len(texts)
|
||||
|
||||
|
||||
class _FakeClientHandle:
|
||||
"""Mirrors the OpenAI client handle the SDK exposes: retries default to 2."""
|
||||
|
||||
def __init__(self):
|
||||
self.max_retries = 2
|
||||
|
||||
|
||||
class FakeLlm:
|
||||
"""Deterministic extraction: echoes the batch key as one ADD result."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.client = _FakeClientHandle()
|
||||
|
||||
def generate_response(self, messages=None, **kwargs):
|
||||
self.calls.append(messages)
|
||||
@@ -135,7 +160,26 @@ def fake_mem0(monkeypatch, tmp_path):
|
||||
POINT_LOG.clear()
|
||||
FakeMemory.instances.clear()
|
||||
monkeypatch.setitem(sys.modules, "mem0", types.ModuleType("mem0"))
|
||||
monkeypatch.setitem(sys.modules, "qdrant_client", types.ModuleType("qdrant_client"))
|
||||
qdrant = types.ModuleType("qdrant_client")
|
||||
models = types.ModuleType("qdrant_client.models")
|
||||
|
||||
@dataclass
|
||||
class MatchValue:
|
||||
value: object = None
|
||||
|
||||
@dataclass
|
||||
class FieldCondition:
|
||||
key: str = ""
|
||||
match: object = None
|
||||
|
||||
@dataclass
|
||||
class Filter:
|
||||
must: list | None = None
|
||||
|
||||
models.Filter, models.FieldCondition, models.MatchValue = Filter, FieldCondition, MatchValue
|
||||
qdrant.models = models
|
||||
monkeypatch.setitem(sys.modules, "qdrant_client", qdrant)
|
||||
monkeypatch.setitem(sys.modules, "qdrant_client.models", models)
|
||||
sys.modules["mem0"].Memory = FakeMemory
|
||||
sys.modules["mem0"]._TEST_EMBEDDER = FakeEmbedder()
|
||||
return ledger_path
|
||||
|
||||
+3
-1
@@ -6,6 +6,7 @@ from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
from conftest import engineering_budget
|
||||
from fastapi.testclient import TestClient
|
||||
from test_api import CREATE, ControlledLLM, events, live_server, turn
|
||||
|
||||
@@ -82,7 +83,8 @@ class R2LLM(ControlledLLM):
|
||||
|
||||
def app_for(tmp_path, *, enabled=True, provider=None, poll=3600):
|
||||
provider = provider or R2LLM()
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)},
|
||||
budget=engineering_budget())
|
||||
app = create_app(db_path=tmp_path / "r2.db", router=router,
|
||||
life_config=LifeConfig(enabled=enabled, poll_seconds=poll))
|
||||
return app, provider
|
||||
|
||||
+4
-2
@@ -8,6 +8,7 @@ from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from conftest import engineering_budget
|
||||
from fastapi.testclient import TestClient
|
||||
from test_api import CREATE, ControlledLLM, events, live_server, make_app, turn
|
||||
from test_r2 import ack, add_life, app_for, final_and_receipt
|
||||
@@ -70,7 +71,8 @@ class GistLLM(ControlledLLM):
|
||||
def memory(tmp_path):
|
||||
with Store(tmp_path / 'memory.db') as s:
|
||||
p = GistLLM()
|
||||
router = build_router(providers={t: p for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
router = build_router(providers={t: p for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)},
|
||||
budget=engineering_budget())
|
||||
clock = [1000.0]
|
||||
yield Memories(s, router, load_settings().models, clock=lambda: clock[0]), p, clock
|
||||
|
||||
@@ -370,7 +372,7 @@ def test_real_chat_retrieval_excludes_twenty_turns_and_preserves_birth(tmp_path,
|
||||
def test_startup_factory_clock_precedes_recovery(tmp_path, monkeypatch):
|
||||
path = tmp_path / 'chat.db'
|
||||
with Store(path) as s:
|
||||
router = build_router(providers={Tier.LOW: ControlledLLM()})
|
||||
router = build_router(providers={Tier.LOW: ControlledLLM()}, budget=engineering_budget())
|
||||
mem = Memories(s, router, load_settings().models)
|
||||
seed(mem, gist=False)
|
||||
with s.conn:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from conftest import engineering_budget
|
||||
from fastapi.testclient import TestClient
|
||||
from test_api import CREATE, events, turn
|
||||
from test_r2 import LIFE, R2LLM
|
||||
@@ -41,7 +42,8 @@ class R4LLM(R2LLM):
|
||||
|
||||
def r4_app(tmp_path, *, enabled=True, provider=None, semantic="stub", poll=3600):
|
||||
provider = provider or R4LLM()
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)},
|
||||
budget=engineering_budget())
|
||||
app = create_app(db_path=tmp_path / "r4.db", router=router,
|
||||
life_config=LifeConfig(enabled=enabled, poll_seconds=poll),
|
||||
semantic_mode=semantic)
|
||||
|
||||
@@ -3,6 +3,7 @@ import json
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
from conftest import engineering_budget
|
||||
from test_api import ControlledLLM
|
||||
|
||||
from cybergril.config import CharacterConfig, ModelsConfig
|
||||
@@ -75,7 +76,8 @@ def setup(store, *, hour=10, days_ago=0.0, intimacy=0.5, arousal=(0.7, 0.9), llm
|
||||
)
|
||||
if intimacy is not None:
|
||||
store.save_dyad(trust=0.6, intimacy=intimacy, debt=0.0, security=0.6, unresolved=[])
|
||||
router = build_router(providers={t: (llm or ReachLLM()) for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
router = build_router(providers={t: (llm or ReachLLM()) for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)},
|
||||
budget=engineering_budget())
|
||||
character = CharacterConfig(identity={"y": 2000, "m": 1, "d": 1, "h": 12})
|
||||
models = ModelsConfig()
|
||||
persona = Persona(store, router, models, enabled=True)
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
"""HEL-882 SDK-boundary recovery: hidden retries, swallowed failures, resumes.
|
||||
|
||||
Fake-SDK mirror of the manager's independent review reproductions (real pinned
|
||||
mem0ai 2.2.1 behavior mirrored from source):
|
||||
|
||||
1. llm_cap=1 against a 500-ing gateway fired 6 HTTP requests (OpenAI default
|
||||
max_retries=2) while llm_ops used stayed 0 → retries now disabled at the
|
||||
client and every wire-hit (even a 5xx) settles as used.
|
||||
2. embed_cap exhausting mid-add: the SDK swallows the embed refusal and returns
|
||||
an empty list; the product used to write sem_batch done/[] and the rows were
|
||||
never organized again → the refusal now re-raises, the batch re-queues
|
||||
without burning an attempt, and raising the cap resumes it.
|
||||
3. stub→mem0 on the same archive: stub coverage blocked the real rebuild →
|
||||
coverage is per-backend now; a real completed batch is never re-sent.
|
||||
"""
|
||||
import contextlib
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
from conftest import engineering_budget
|
||||
from test_mem0_backend import POINT_LOG, FakeEmbedder, FakeMemory, _make_ledger
|
||||
|
||||
from cybergril.memory.semantic import (
|
||||
EmbedLedgerGuard,
|
||||
Mem0Backend,
|
||||
SemanticBudgetError,
|
||||
SemanticMemory,
|
||||
StubBackend,
|
||||
build_semantic,
|
||||
verify_ledger_authority,
|
||||
)
|
||||
from cybergril.memory.store import Store
|
||||
from cybergril.think.budget import BudgetGuard
|
||||
|
||||
|
||||
class Wire500Error(Exception):
|
||||
"""Mirror of openai.APIStatusError: the request WAS answered (500)."""
|
||||
|
||||
|
||||
class NeverConnectedError(Exception):
|
||||
"""Mirror of an openai error whose cause is httpx.ConnectError: unsent."""
|
||||
|
||||
|
||||
def _httpx_connect_error():
|
||||
cls = type("ConnectError", (Exception,), {})
|
||||
cls.__module__ = "httpx"
|
||||
return cls()
|
||||
|
||||
|
||||
class SwallowingMemory(FakeMemory):
|
||||
"""Mirror of 2.2.1's phase-3/7 fallback: embed failures in add() are
|
||||
swallowed into an empty result — the exact review reproduction."""
|
||||
|
||||
def add(self, text, metadata=None, user_id=None):
|
||||
self.embedding_model.embed(text, memory_action="search") # phase 1
|
||||
self.llm.generate_response(messages=[
|
||||
{"role": "system", "content": "extract"},
|
||||
{"role": "user", "content": text},
|
||||
], response_format={"type": "json_object"})
|
||||
extracted = f"提取:{text[:20]}"
|
||||
try: # phase 3
|
||||
self.embedding_model.embed_batch([extracted], memory_action="add")
|
||||
except Exception:
|
||||
embed_map = {}
|
||||
with contextlib.suppress(Exception):
|
||||
embed_map[self.embedding_model.embed( # noqa: F841 — fallback mirror
|
||||
extracted, memory_action="add")] = None
|
||||
if not embed_map:
|
||||
return [] # ← the swallow the review caught
|
||||
self.seq += 1
|
||||
entry_id = f"m{self.seq}"
|
||||
bucket = POINT_LOG.setdefault(self.collection, {})
|
||||
bucket[entry_id] = {"data": extracted, "user_id": user_id, **(metadata or {})}
|
||||
return {"results": [{"id": entry_id, "memory": extracted, "event": "ADD"}]}
|
||||
|
||||
|
||||
def install_fake(monkeypatch, memory_cls=FakeMemory):
|
||||
POINT_LOG.clear()
|
||||
FakeMemory.instances.clear()
|
||||
monkeypatch.setitem(sys.modules, "mem0", types.ModuleType("mem0"))
|
||||
qdrant = types.ModuleType("qdrant_client")
|
||||
models = types.ModuleType("qdrant_client.models")
|
||||
|
||||
class MatchValue:
|
||||
def __init__(self, value=None):
|
||||
self.value = value
|
||||
|
||||
class FieldCondition:
|
||||
def __init__(self, key="", match=None):
|
||||
self.key, self.match = key, match
|
||||
|
||||
class Filter:
|
||||
def __init__(self, must=None):
|
||||
self.must = must
|
||||
|
||||
models.Filter, models.FieldCondition, models.MatchValue = Filter, FieldCondition, MatchValue
|
||||
qdrant.models = models
|
||||
monkeypatch.setitem(sys.modules, "qdrant_client", qdrant)
|
||||
monkeypatch.setitem(sys.modules, "qdrant_client.models", models)
|
||||
sys.modules["mem0"].Memory = memory_cls
|
||||
sys.modules["mem0"]._TEST_EMBEDDER = FakeEmbedder()
|
||||
return sys.modules["mem0"]
|
||||
|
||||
|
||||
def config_for(tmp_path, ledger, *, embed_cap=10, llm_cap=10, **extra):
|
||||
config = {
|
||||
"gateway_base_url": "http://127.0.0.1:9/v1",
|
||||
"gateway_model": "fake",
|
||||
"vector_root": str(tmp_path / "vec"),
|
||||
"history_root": str(tmp_path / "hist"),
|
||||
"collection": "cg_public",
|
||||
"ledger_path": str(ledger),
|
||||
"embed_cap": embed_cap,
|
||||
"llm_cap": llm_cap,
|
||||
}
|
||||
config.update(extra)
|
||||
return config
|
||||
|
||||
|
||||
def seed_turn(store, turn_id, text):
|
||||
with store.conn:
|
||||
store.execute(
|
||||
"INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES(1,'user',?,?,'sent')",
|
||||
(text, turn_id),
|
||||
)
|
||||
row = store.query_one("SELECT id FROM chat_message WHERE turn_id=?", (turn_id,))
|
||||
return [{"message_id": row["id"], "turn_id": turn_id, "role": "user", "text": text}]
|
||||
|
||||
|
||||
async def test_hidden_retries_disabled_and_wire_hits_counted(tmp_path, monkeypatch):
|
||||
"""Review repro 1: llm_cap=1, gateway 500s → exactly ONE HTTP attempt, and
|
||||
it lands in llm_ops; the second add refuses before the wire."""
|
||||
from test_mem0_backend import FakeLlm
|
||||
|
||||
class Failing500Llm(FakeLlm):
|
||||
"""The wire answer is a 500: raised inside generate_response like the
|
||||
real OpenAI client does (an answered request, definitively sent)."""
|
||||
|
||||
def generate_response(self, messages=None, **kwargs):
|
||||
self.calls.append("wire")
|
||||
raise Wire500Error("HTTP 500 review controlled")
|
||||
|
||||
class Failing500Memory(FakeMemory):
|
||||
def __init__(self, embedder, collection):
|
||||
super().__init__(embedder, collection)
|
||||
self.llm = Failing500Llm()
|
||||
|
||||
install_fake(monkeypatch, Failing500Memory)
|
||||
ledger = tmp_path / "retry.sqlite3"
|
||||
_make_ledger(ledger)
|
||||
backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=1))
|
||||
assert backend._memory.llm.client.max_retries == 0 # hidden retries disabled
|
||||
rows = [{"message_id": 1, "turn_id": "t1", "role": "user", "text": "合成"}]
|
||||
anchor = {"turn_ids": ["t1"], "turn_roles": [["t1", "user", 1]], "input_sha256": "x"}
|
||||
with pytest.raises(Wire500Error):
|
||||
await backend.add_group(rows, anchor, "retry")
|
||||
assert len(backend._memory.llm.calls) == 1 # one actual send, no SDK retries
|
||||
assert backend.llm_guard.used() == 1 # the answered 5xx is COUNTED
|
||||
# second add: cap 1/1 used → refuses before any wire hit
|
||||
calls_before = len(backend._memory.llm.calls)
|
||||
with pytest.raises(RuntimeError, match="semantic_llm_budget_exhausted"):
|
||||
await backend.add_group(rows, anchor, "retry2")
|
||||
assert len(backend._memory.llm.calls) == calls_before
|
||||
|
||||
|
||||
async def test_pre_connection_failure_releases(tmp_path, monkeypatch):
|
||||
"""Only a provably-unsent request (httpx.ConnectError cause) releases."""
|
||||
mem0 = install_fake(monkeypatch)
|
||||
|
||||
class UnsentMemory(FakeMemory):
|
||||
def add(self, text, metadata=None, user_id=None):
|
||||
self.embedding_model.embed(text, memory_action="search")
|
||||
exc = NeverConnectedError("connection refused")
|
||||
exc.__cause__ = _httpx_connect_error()
|
||||
raise exc
|
||||
|
||||
mem0.Memory = UnsentMemory
|
||||
ledger = tmp_path / "unsent.sqlite3"
|
||||
_make_ledger(ledger)
|
||||
backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=5))
|
||||
rows = [{"message_id": 1, "turn_id": "t", "role": "user", "text": "x"}]
|
||||
with pytest.raises(NeverConnectedError):
|
||||
await backend.add_group(rows, {"turn_ids": ["t"], "turn_roles": [["t", "user", 1]],
|
||||
"input_sha256": "x"}, "unsent")
|
||||
assert backend.llm_guard.used() == 0 # nothing reached the wire → released
|
||||
|
||||
|
||||
async def test_mid_add_budget_swallow_requeues_then_resumes(tmp_path, monkeypatch):
|
||||
"""Review repro 2: embed cap exhausts mid-add, the SDK swallows it — the
|
||||
batch must NOT complete empty; raising the cap resumes and organizes."""
|
||||
install_fake(monkeypatch, SwallowingMemory)
|
||||
ledger = tmp_path / "exhaust.sqlite3"
|
||||
_make_ledger(ledger)
|
||||
backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=1, llm_cap=5))
|
||||
store = Store(tmp_path / "exhaust.db")
|
||||
seed_turn(store, "t1", "合成测试钥匙在第三个花盆下面")
|
||||
semantic = SemanticMemory(store, backend)
|
||||
semantic.enqueue_uncovered()
|
||||
await semantic.tick()
|
||||
after_first = dict(store.query_one("SELECT state,reason,entry_ids,attempts FROM sem_batch"))
|
||||
assert after_first["state"] == "queued" # NOT done: the swallow was caught
|
||||
assert "budget" in (after_first["reason"] or "")
|
||||
assert after_first["attempts"] == 0 # budget refusal burns no attempt
|
||||
assert json.loads(after_first["entry_ids"] or "[]") == []
|
||||
|
||||
backend.ledger.cap = 50 # the manager raises the approved cap
|
||||
await semantic.tick()
|
||||
after_raise = dict(store.query_one("SELECT state,reason,entry_ids,attempts FROM sem_batch"))
|
||||
assert after_raise["state"] == "done" # resumed and organized the same rows
|
||||
assert json.loads(after_raise["entry_ids"])
|
||||
hits = await backend.search("合成测试钥匙")
|
||||
assert hits
|
||||
store.close()
|
||||
|
||||
|
||||
async def test_resume_never_loses_or_duplicates_rows(tmp_path, monkeypatch):
|
||||
"""A crash mid-batch (row1 stored, row2 not) resumes sending ONLY row2."""
|
||||
install_fake(monkeypatch)
|
||||
ledger = tmp_path / "resume.sqlite3"
|
||||
_make_ledger(ledger)
|
||||
backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=50))
|
||||
store = Store(tmp_path / "resume.db")
|
||||
rows = seed_turn(store, "t2", "第一条原话")
|
||||
with store.conn: # a shared companion row joins the turn
|
||||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
|
||||
"(2,'companion','第二条原话','t2','sent')")
|
||||
row2 = store.query_one("SELECT id FROM chat_message WHERE text='第二条原话'")
|
||||
rows.append({"message_id": row2["id"], "turn_id": "t2", "role": "companion", "text": "第二条原话"})
|
||||
anchor = {"turn_ids": ["t2", "t2"], "turn_roles": [["t2", "user", rows[0]["message_id"]],
|
||||
["t2", "companion", rows[1]["message_id"]]],
|
||||
"input_sha256": "x"}
|
||||
# simulate: attempt 1 stored row1's entry then died (e.g. crash before commit)
|
||||
point_id = "pre-stored-1"
|
||||
POINT_LOG.setdefault("cg_public", {})[point_id] = {
|
||||
"data": "提取:第一条原话", "user_id": "cybergril",
|
||||
"src_group": "chat_public:mem0:t2:key",
|
||||
"turn_roles": [["t2", "user", rows[0]["message_id"]]],
|
||||
"input_sha256": "x",
|
||||
}
|
||||
created = await backend.add_group(rows, anchor, "chat_public:mem0:t2:key")
|
||||
texts_added = [backend.payload(e["id"])["data"] for e in created]
|
||||
assert len(created) == 1 # only the missing row was sent
|
||||
assert "第二条原话" in texts_added[0]
|
||||
completed = backend.completed_message_ids("chat_public:mem0:t2:key")
|
||||
assert completed == {rows[0]["message_id"], rows[1]["message_id"]}
|
||||
# nothing left to send → idempotent no-op
|
||||
assert await backend.add_group(rows, anchor, "chat_public:mem0:t2:key") == []
|
||||
store.close()
|
||||
|
||||
|
||||
async def test_stub_batches_never_block_real_rebuild_and_real_never_resends(tmp_path, monkeypatch):
|
||||
"""Review repro 3: stub→mem0 on the same archive reorganizes; a real done
|
||||
batch is never re-enqueued nor re-sent."""
|
||||
install_fake(monkeypatch)
|
||||
store = Store(tmp_path / "switch.db")
|
||||
seed_turn(store, "t3", "另一条合成原话")
|
||||
|
||||
stub = SemanticMemory(store, StubBackend())
|
||||
stub.enqueue_uncovered()
|
||||
await stub.tick()
|
||||
prior = dict(store.query_one("SELECT backend,state,entry_ids FROM sem_batch"))
|
||||
assert prior["backend"] == "stub" and prior["state"] == "done"
|
||||
|
||||
ledger = tmp_path / "switch.sqlite3"
|
||||
_make_ledger(ledger)
|
||||
backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=50))
|
||||
live = SemanticMemory(store, backend)
|
||||
assert live.enqueue_uncovered() == 1 # stub coverage does NOT block mem0
|
||||
await live.tick()
|
||||
batches = store.query("SELECT backend,state FROM sem_batch ORDER BY id")
|
||||
assert [b["backend"] for b in batches] == ["stub", "mem0"]
|
||||
assert batches[1]["state"] == "done"
|
||||
hits = await backend.search("另一条合成原话")
|
||||
assert hits # the real backend actually holds the row now
|
||||
# a real completed batch is never re-sent
|
||||
assert live.enqueue_uncovered() == 0
|
||||
assert await backend.add_group(
|
||||
[{"message_id": store.query_one("SELECT id FROM chat_message WHERE turn_id='t3'")["id"],
|
||||
"turn_id": "t3", "role": "user", "text": "另一条合成原话"}],
|
||||
{"turn_ids": ["t3"], "turn_roles": [], "input_sha256": "x"},
|
||||
store.query_one("SELECT batch_key FROM sem_batch WHERE backend='mem0'")["batch_key"],
|
||||
) == []
|
||||
store.close()
|
||||
|
||||
|
||||
async def test_embed_daily_cap_enforced_in_same_reserve(tmp_path):
|
||||
"""Execution-table C per-day embed top applies inside the atomic reserve."""
|
||||
ledger = tmp_path / "daily.sqlite3"
|
||||
_make_ledger(ledger)
|
||||
guard = EmbedLedgerGuard(ledger, cap=50, daily_cap=1)
|
||||
guard.settle(guard.reserve(1, "search"), "search")
|
||||
assert guard.used() == 1
|
||||
with pytest.raises(RuntimeError, match="semantic_embed_budget_daily_exhausted"):
|
||||
guard.reserve(1, "search") # lifetime cap 50 still has room — day top hit
|
||||
|
||||
|
||||
async def test_mem0_internal_llm_goes_through_the_unified_request_gate(tmp_path, monkeypatch):
|
||||
"""The SDK's hidden extraction LLM reserves request count + tokens in the
|
||||
product guard (category 'semantic') before the wire."""
|
||||
install_fake(monkeypatch)
|
||||
ledger = tmp_path / "unified.sqlite3"
|
||||
_make_ledger(ledger)
|
||||
request_guard = BudgetGuard(engineering_budget(daily_requests={"semantic": 1}))
|
||||
backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=50),
|
||||
request_guard=request_guard)
|
||||
store = Store(tmp_path / "unified.db")
|
||||
rows = seed_turn(store, "t4", "统一闸测试")
|
||||
await backend.add_group(rows, {"turn_ids": ["t4"], "turn_roles": [["t4", "user", 1]],
|
||||
"input_sha256": "x"}, "u1")
|
||||
assert request_guard.requests_used("semantic") == 1
|
||||
assert request_guard.used > 0 # conservative tokens pre-allocated too
|
||||
with pytest.raises(Exception, match="budget_requests_exhausted:semantic"):
|
||||
seed_turn(store, "t5", "第二次")
|
||||
rows2 = [{"message_id": store.query_one(
|
||||
"SELECT id FROM chat_message WHERE turn_id='t5'")["id"],
|
||||
"turn_id": "t5", "role": "user", "text": "第二次"}]
|
||||
await backend.add_group(rows2, {"turn_ids": ["t5"], "turn_roles": [["t5", "user", 2]],
|
||||
"input_sha256": "x"}, "u2")
|
||||
store.close()
|
||||
|
||||
|
||||
def test_authority_block_refuses_a_fresh_file_bypassing_the_freeze(tmp_path):
|
||||
"""A new empty ledger must not re-open the frozen 498/500 headroom."""
|
||||
authority_ledger = tmp_path / "authoritative.sqlite3"
|
||||
conn = sqlite3.connect(str(authority_ledger))
|
||||
with conn:
|
||||
conn.execute("CREATE TABLE embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT,"
|
||||
" pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
|
||||
conn.execute("INSERT INTO embed_ops(ts,pid,kind,items,note) VALUES"
|
||||
"('2026-10-20T01:00:00Z',1,'dense',498,'product:frozen')")
|
||||
conn.close()
|
||||
|
||||
import hashlib
|
||||
|
||||
rows = sqlite3.connect(str(authority_ledger)).execute(
|
||||
"SELECT ts,pid,kind,items,note FROM embed_ops ORDER BY id LIMIT 1").fetchall()
|
||||
digest = hashlib.sha256(
|
||||
"\n".join("|".join(str(c) for c in row) for row in rows).encode()).hexdigest()
|
||||
authority = {"prefix_rows": 1, "prefix_sha256": digest, "min_used": 498}
|
||||
|
||||
# the authoritative file itself passes
|
||||
verify_ledger_authority(authority_ledger, authority)
|
||||
|
||||
# a different (fresh) file with an approved cap is refused
|
||||
fresh = tmp_path / "fresh-bypass.sqlite3"
|
||||
conn = sqlite3.connect(str(fresh))
|
||||
with conn:
|
||||
conn.execute("CREATE TABLE embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT,"
|
||||
" pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
|
||||
conn.close()
|
||||
with pytest.raises(SemanticBudgetError):
|
||||
verify_ledger_authority(fresh, authority)
|
||||
with pytest.raises(SemanticBudgetError, match="ledger_authority_missing_file"):
|
||||
verify_ledger_authority(tmp_path / "not-there.sqlite3", authority)
|
||||
|
||||
|
||||
async def test_build_semantic_mem0_fail_closed_on_authority_mismatch(tmp_path, monkeypatch):
|
||||
install_fake(monkeypatch)
|
||||
fresh = tmp_path / "fresh2.sqlite3"
|
||||
conn = sqlite3.connect(str(fresh))
|
||||
with conn:
|
||||
conn.execute("CREATE TABLE embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT,"
|
||||
" pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
|
||||
conn.execute("CREATE TABLE llm_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT,"
|
||||
" pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
|
||||
conn.close()
|
||||
store = Store(tmp_path / "fc.db")
|
||||
assert build_semantic(
|
||||
store, mode="mem0",
|
||||
config=config_for(tmp_path, fresh, embed_cap=10, llm_cap=10,
|
||||
authority={"prefix_rows": 1, "prefix_sha256": "0" * 64,
|
||||
"min_used": 498}),
|
||||
) is None # fail closed: semantic layer off, never a silent stub swap
|
||||
store.close()
|
||||
Reference in New Issue
Block a user