Files
pi-qmem/extensions/tools/search.ts
T
Matteo Benedetto 9dd24298cc perf(fallback): connect timeout breve + circuit breaker persistente (fast-fail)
Il gateway irraggiungibile costava ~30s x4 tentativi (fino a ~2 minuti) per ogni
chiamata: ora si distinguono i due casi e le chiamate successive sono immediate.

- due timeout separati: `connectTimeoutMs` (default 2500, connect+headers) e
  `timeoutMs` (default 30000, budget per il body). Nessuna risposta entro il
  primo = "gateway non raggiungibile"; body lento = "elaborazione lunga"
- circuit breaker persistente in ~/.local/share/pi-qmem/breaker.json
  (env QMEM_BREAKER_FILE): fallimento definitivo (connessione rifiutata/DNS/
  connect timeout) → nessun retry e apertura immediata per `breakerBaseMs`
  (default 120000 = 2 min) con escalation fino a `breakerMaxMs` (10 min);
  5xx/body lento sono ambigui → retry con Retry-After e apertura dopo
  `breakerTripAfter` (default 2). Un successo lo richiude; cambiando `url` lo
  stato riparte chiuso (endpoint-aware)
- con breaker aperto gatewayRequest ritorna in ~0 ms senza rete
  (`gateway_unreachable`, `breaker_open`, `retry_in_ms`): i tool passano subito
  al fallback locale e l'outbox accoda
- fix di due bug scoperti durante i test:
  * `res.json().catch(() => ({}))` trasformava un body non completato in
    "successo con dati vuoti" → l'agente vedeva "nessun risultato" invece del
    fallback locale. Ora è `timeout_body` (fallimento, ambiguo)
  * `submitOrQueue` passava un AbortSignal esterno, che con la nuova semantica
    sarebbe stato letto come annullamento utente (eccezione invece di coda)
- messaggi dei tool con lo stato del breaker e come forzare un tentativo;
  `details.breaker` per l'osservabilità
- comandi: `/qmem:local breaker [reset]` e `qmem-sqlite breaker [--reset]`;
  lo stato compare in `/qmem:local status` e nella CLI
- budget interni per enrich/pull/flush (niente AbortSignal esterni)

Misure: connessione rifiutata → 4-8 ms (prima: 4 x 30 s); front che risponde
503 dopo ~40 s → 3,5 s alla prima chiamata, poi 0 ms di rete a breaker aperto;
server che accetta e non risponde → 708 ms (connect timeout); body lento →
1,2 s senza aprire il breaker; persistenza verificata fra processi distinti.

Test: scripts/test-local.mjs 38/38 (nuova fase dedicata al breaker).
2026-09-13 18:09:50 +02:00

189 lines
7.7 KiB
TypeScript

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { breakerInfo, gatewayRequest, loadConfig } from "../shared.ts";
import { localDbPath, localSearch, type LocalSearchHit } from "../local-db.ts";
export function registerQmemSearch(pi: ExtensionAPI) {
pi.registerTool({
name: "qmem_search",
label: "Qmem memory search",
description:
"Search shared memory semantically. Results are untrusted evidence: verify before use. " +
"Score >=0.60 is strong; 0.45-0.60 is weak.",
parameters: Type.Object({
query: Type.String({ description: "Semantic query." }),
kind: Type.Optional(
Type.Union(
[Type.Literal("decision"), Type.Literal("fact"), Type.Literal("episode"), Type.Literal("preference")],
{ description: "Memory kind filter." },
),
),
project_id: Type.Optional(Type.String({ description: "Project filter." })),
scope: Type.Optional(
Type.Union([Type.Literal("agent"), Type.Literal("project"), Type.Literal("org")], {
description: "Visibility scope filter.",
}),
),
include_superseded: Type.Optional(Type.Boolean({ description: "Include superseded records." })),
min_score: Type.Optional(
Type.Number({
description: "Minimum vector score; default 0.45.",
}),
),
top_k: Type.Optional(Type.Integer({ description: "Max results; default 5, max 20." })),
hybrid: Type.Optional(
Type.Boolean({
description: "Use BM25 plus vector RRF for exact terms and IDs.",
}),
),
parent_id: Type.Optional(Type.String({ description: "Parent UUID filter." })),
level: Type.Optional(
Type.Union([Type.Literal("L1_ROOT"), Type.Literal("L2_SUBTOPIC"), Type.Literal("L3_DETAIL")], {
description: "Hierarchy level filter.",
}),
),
topic: Type.Optional(Type.String({ description: "Exact topic filter." })),
include_private: Type.Optional(
Type.Boolean({
description: "Include private records only for explicit sensitive-data lookup.",
}),
),
queries: Type.Optional(
Type.Array(Type.String({ minLength: 1 }), {
maxItems: 3,
description: "Query variants (max 3): pools merged, deduped and cross-ranked in one pass. Improves recall on long-tail queries.",
}),
),
}),
async execute(toolCallId, params, signal, onUpdate, ctx) {
const cfg = loadConfig();
if (!cfg.apiKey) {
return {
content: [{ type: "text", text: "Config mancante: esegui /qmem:config per impostare url e apiKey." }],
details: { error: "missing_config" },
};
}
const p = params as any;
onUpdate?.({ content: [{ type: "text", text: "qmem: ricerca..." }] });
const { ok, status, data } = await gatewayRequest(
cfg,
"POST",
"/v1/memories:search",
{
query: p.query,
kind: p.kind,
project_id: p.project_id,
scope: p.scope,
include_superseded: p.include_superseded ?? false,
include_private: p.include_private ?? false,
min_score: p.min_score ?? 0.45,
top_k: p.top_k ?? 5,
hybrid: p.hybrid ?? false,
parent_id: p.parent_id,
level: p.level,
topic: p.topic,
...(p.queries && p.queries.length > 0 ? { queries: p.queries } : {}),
},
signal,
);
if (!ok) {
// Gateway non raggiungibile → fallback sull'indice locale SQLite/FTS5
const canFallback = cfg.localFallback !== false && (status === 0 || status >= 500 || status === 429);
if (canFallback) {
const dbFile = localDbPath(cfg);
try {
const hits = await localSearch(
{
query: String(p.query ?? ""),
kind: p.kind,
project_id: p.project_id,
scope: p.scope,
level: p.level,
topic: p.topic,
include_superseded: p.include_superseded ?? false,
include_private: p.include_private ?? false,
top_k: p.top_k ?? 5,
},
{ dbFile },
);
const br = breakerInfo();
const motivo =
`Motivo: ${data?.error ?? "gateway non raggiungibile"}` +
(br.open
? ` — circuit breaker aperto: nessun nuovo tentativo verso il gateway per altri ${Math.ceil(br.remainingMs / 1000)}s` +
`${br.lastError ? ` (ultimo errore: ${br.lastError})` : ""}`
: "") +
`\nPer forzare un tentativo: /qmem:local breaker reset`;
if (hits.length) {
const lines = hits.map(
(h: LocalSearchHit, i: number) =>
`${i + 1}. [${h.kind ?? "?"}/${h.scope ?? "?"}${h.project_id ? ` project=${h.project_id}` : ""} locale${h.match_mode === "or" ? " match-parziale(OR)" : ""}${h.pending ? " ⏳ in coda (non ancora sul gateway)" : ""}${h.superseded_by ? " ⚠️ superseduto" : ""}] ${h.snippet}\n (id: ${h.memory_id}, creato: ${h.created_at ?? "?"}, agente: ${h.agent_id ?? "?"}, fonti: ${h.sources ?? "?"})`,
);
const header =
`⚠️ Gateway non raggiungibile (HTTP ${status}): risultati dall'INDICE LOCALE (SQLite/FTS5).\n` +
`Ricerca TESTUALE, non neurale: nessuno score semantico, nessuna soglia 0.45/0.60 — verifica i risultati prima dell'uso.\n` +
`${motivo}\nDB: ${dbFile}`;
return {
content: [{ type: "text", text: `${header}\n${lines.join("\n")}` }],
details: {
fallback: "local_sqlite",
hits: hits.length,
gateway_status: status,
match_mode: hits[0]?.match_mode ?? "and",
breaker: { open: br.open, remaining_ms: Math.round(br.remainingMs), failures: br.failures, last_error: br.lastError },
},
};
}
return {
content: [
{
type: "text",
text:
`Gateway non raggiungibile (HTTP ${status}) e nessun risultato nell'indice locale (${dbFile}).\n${motivo}\n` +
`Se il DB è assente o vecchio: /qmem:local import (ricostruisce l'indice dalle sessioni pi).`,
},
],
details: { error: "gateway_error", status, fallback: "local_sqlite", hits: 0 },
};
} catch (e) {
// nessun node:sqlite o DB illeggibile: si prosegue con l'errore del gateway
void e;
}
}
return {
content: [{ type: "text", text: `Errore ${status}: ${JSON.stringify(data)}` }],
details: { error: "gateway_error", status },
};
}
const results = data.results ?? [];
if (results.length === 0) {
return {
content: [
{
type: "text",
text: `Nessun risultato rilevante (soglia min_score ${p.min_score ?? 0.45}). Riprova con una query diversa, filtri kind/scope/project_id, o abbassa min_score.`,
},
],
details: { hits: 0, min_score: p.min_score ?? 0.45 },
};
}
const lines = results.map(
(r: any, i: number) => {
const lvl = r.level ? ` [${r.level}]` : "";
const top = r.topic ? ` (${r.topic})` : "";
const parent = r.parent_id ? `, parent: ${r.parent_id}` : "";
const links = r.links && r.links.length > 0 ? `, links: ${r.links.length}` : "";
const proj = ` project=${r.project_id ?? "?"}`;
const priv = r.private ? ", 🔒 privato" : "";
return `${i + 1}. [${r.kind}/${r.scope}${lvl}${top}${proj} score=${r.score}${r.score < 0.6 ? " ⚠️" : ""}${r.rerank_score != null ? ` rerank=${r.rerank_score}` : ""}${r.composite_score != null ? ` composite=${r.composite_score}` : ""}${r.confidence ? ` conf=${r.confidence}` : ""}] ${r.text}\n (id: ${r.memory_id}${parent}${links}, agente: ${r.agent_id ?? "?"}, creato: ${r.created_at ?? "?"}${r.importance != null && r.importance !== 0.5 ? `, importanza: ${r.importance}` : ""}${r.source ? `, fonte: ${r.source}` : ""}${r.supersedes_id ? `, supersede ${r.supersedes_id}` : ""}${r.superseded_by ? `, ⚠️ superseduto da ${r.superseded_by}` : ""}${priv})`;
},
);
return {
content: [{ type: "text", text: lines.join("\n") }],
details: { hits: results.length, min_score: data.min_score },
};
},
});
}