Files
pi-qmem/extensions/tools/get.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

103 lines
4.4 KiB
TypeScript

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { gatewayRequest, loadConfig } from "../shared.ts";
import { localDbPath, localGet } from "../local-db.ts";
import { breakerInfo } from "../shared.ts";
export function registerQmemGet(pi: ExtensionAPI) {
pi.registerTool({
name: "qmem_get",
label: "Qmem memory get by ID",
description:
"Fetch one record exactly by UUID, including superseded records. Use qmem_search when the UUID is unknown.",
parameters: Type.Object({
memory_id: Type.String({ description: "Record UUID." }),
}),
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: recupero record ${p.memory_id}...` }] });
const { ok, status, data } = await gatewayRequest(cfg, "GET", `/v1/memories/${p.memory_id}`, undefined, signal);
if (!ok) {
const notFound = status === 404 || data?.detail === "Memoria non trovata";
// Anche sul 404 si consulta l'indice locale: l'id può essere di un record
// creato offline (in coda, non ancora sul gateway).
{
try {
const local = await localGet(p.memory_id, { dbFile: localDbPath(cfg) });
if (local) {
const br = breakerInfo();
const origine = notFound
? "non presente sul gateway (404): record dall'INDICE LOCALE"
: `gateway non raggiungibile (HTTP ${status}): record dall'INDICE LOCALE` +
(br.open ? ` — circuit breaker aperto (riprova tra ${Math.ceil(br.remainingMs / 1000)}s)` : "");
return {
content: [
{
type: "text",
text:
`⚠️ ${origine} (osservazione più vecchia del gateway, può essere incompleta).\n` +
`memory_id: ${local.memory_id}\n[${local.kind ?? "?"}/${local.scope ?? "?"}${local.project_id ? ` project=${local.project_id}` : ""}] agente: ${local.agent_id ?? "?"}, creato: ${local.created_at ?? "?"}${local.pending ? ", ⏳ creato offline: non ancora sul gateway" : ""}${local.superseded_by ? `, ⚠️ superseduto da ${local.superseded_by}` : ""}${local.deleted_at ? `, 🗑 cancellato sul gateway (${local.deleted_at})` : ""}${local.remote_id ? `, sincronizzato come ${local.remote_id}` : ""}\n\n${local.text ?? "(nessun testo)"}`,
},
],
details: {
memory_id: local.memory_id,
fallback: "local_sqlite",
gateway_status: status,
pending: local.pending === 1,
breaker: { open: br.open, remaining_ms: Math.round(br.remainingMs) },
},
};
}
} catch {
/* indice locale non disponibile: si prosegue con l'errore del gateway */
}
}
return {
content: [
{
type: "text",
text: notFound
? `Record ${p.memory_id} non trovato (404). Verifica l'ID (qmem_search include_superseded=true per la lineage) oppure l'URL gateway.`
: `Errore ${status}: ${JSON.stringify(data)}`,
},
],
details: { error: notFound ? "not_found" : "gateway_error", status, memory_id: p.memory_id },
};
}
const r = data ?? {};
const meta = [
`[${r.kind ?? "?"}/${r.scope ?? "?"}${r.level ? ` ${r.level}` : ""}${r.topic ? ` (${r.topic})` : ""}${r.confidence ? ` conf=${r.confidence}` : ""}]`,
`project: ${r.project_id ?? "?"}`,
`agente: ${r.agent_id ?? "?"}, creato: ${r.created_at ?? "?"}${r.source ? `, fonte: ${r.source}` : ""}`,
];
if (r.parent_id) meta.push(`parent: ${r.parent_id}`);
if (r.links && r.links.length > 0) meta.push(`links: ${r.links.length}`);
if (r.supersedes_id) meta.push(`supersede ${r.supersedes_id}`);
if (r.superseded_by) meta.push(`⚠️ SUPERSEDUTO da ${r.superseded_by}`);
if (r.expires_at) meta.push(`scade: ${r.expires_at}`);
const lines = [`memory_id: ${r.memory_id ?? p.memory_id}`, meta.join(" | "), "", r.text ?? "(nessun testo)"];
return {
content: [{ type: "text", text: lines.join("\n") }],
details: {
memory_id: r.memory_id ?? p.memory_id,
kind: r.kind,
scope: r.scope,
project_id: r.project_id,
parent_id: r.parent_id,
level: r.level,
topic: r.topic,
superseded_by: r.superseded_by ?? null,
},
};
},
});
}