Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(memory): stop reporting a completed coding-session import as a failure

M3gA-Mind0e2d3d1f5c30
diff --git a/app/src/components/intelligence/CodingSessionsCard.tsx b/app/src/components/intelligence/CodingSessionsCard.tsx
index 915d5eb0d6..1a5f07ea2e 100644
--- a/app/src/components/intelligence/CodingSessionsCard.tsx
+++ b/app/src/components/intelligence/CodingSessionsCard.tsx
@@ -74,18 +74,29 @@ export function CodingSessionsCard({ onToast }: CodingSessionsCardProps) {
shouldStop: () => stopRequestedRef.current,
});
console.debug(
- '[coding-sessions] drain: exit passes=%d processed=%d failed=%d more=%s',
+ '[coding-sessions] drain: exit passes=%d processed=%d failed=%d more=%s timed_out=%s',
result.passes,
result.sessionsProcessed,
result.sessionsFailed,
- result.moreRemaining
+ result.moreRemaining,
+ result.timedOut
);
// Any leftover backlog is incomplete, regardless of why the loop exited —
// a user Stop, the pass cap, or a stalled pass. Only a fully drained run
// (no more budget) is reported as complete success.
const incomplete = result.moreRemaining;
- const message =
- result.sessionsFailed > 0
+ // A deadline outranks a stale failure count. `sessionsFailed` is assigned
+ // from the last *completed* pass, so when a later pass times out it
+ // describes work that is already superseded — while `timedOut` describes
+ // a run that is still going. Leading with the failure would tell the user
+ // to retry something that has not finished, which is the whole defect
+ // this branch exists to stop (#5802).
+ const message = result.timedOut
+ ? t('memorySources.codingSessions.stillRunningMessage').replace(
+ '{processed}',
+ String(result.sessionsProcessed)
+ )
+ : result.sessionsFailed > 0
? t('memorySources.codingSessions.partialFailure')
.replace('{failed}', String(result.sessionsFailed))
.replace('{processed}', String(result.sessionsProcessed))
@@ -96,11 +107,20 @@ export function CodingSessionsCard({ onToast }: CodingSessionsCardProps) {
: t('memorySources.codingSessions.completeMessage')
.replace('{processed}', String(result.sessionsProcessed))
.replace('{observations}', String(result.observations));
- onToast?.({
- type: result.sessionsFailed > 0 ? 'warning' : incomplete ? 'info' : 'success',
- title: incomplete
+ const title = result.timedOut
+ ? t('memorySources.codingSessions.stillRunning')
+ : incomplete
? t('memorySources.codingSessions.stopped')
- : t('memorySources.codingSessions.complete'),
+ : t('memorySources.codingSessions.complete');
+ onToast?.({
+ type: result.timedOut
+ ? 'info'
+ : result.sessionsFailed > 0
+ ? 'warning'
+ : incomplete
+ ? 'info'
+ : 'success',
+ title,
message,
});
await load();
diff --git a/app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx b/app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx
index 382d22a1c4..ec41be6470 100644
--- a/app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx
+++ b/app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx
@@ -54,6 +54,7 @@ describe('CodingSessionsCard', () => {
observations: 6,
remaining: 0,
moreRemaining: false,
+ timedOut: false,
});
const onToast = vi.fn();
renderWithProviders(<CodingSessionsCard onToast={onToast} />);
@@ -98,6 +99,7 @@ describe('CodingSessionsCard', () => {
observations: 3,
remaining: 25,
moreRemaining: true,
+ timedOut: false,
});
return new Promise(resolve => {
finishDrain = () =>
@@ -108,6 +110,7 @@ describe('CodingSessionsCard', () => {
observations: 3,
remaining: 25,
moreRemaining: true,
+ timedOut: false,
});
});
});
@@ -146,6 +149,7 @@ describe('CodingSessionsCard', () => {
observations: 12000,
remaining: 300,
moreRemaining: true,
+ timedOut: false,
});
const onToast = vi.fn();
renderWithProviders(<CodingSessionsCard onToast={onToast} />);
@@ -171,6 +175,7 @@ describe('CodingSessionsCard', () => {
observations: 4,
remaining: 0,
moreRemaining: false,
+ timedOut: false,
});
const onToast = vi.fn();
renderWithProviders(<CodingSessionsCard onToast={onToast} />);
@@ -194,6 +199,66 @@ describe('CodingSessionsCard', () => {
expect(await screen.findByRole('alert')).toHaveTextContent('session scan failed');
});
+ it('does not report a deadline as a failure banner', async () => {
+ // The defect this test exists for (#5802): the import completes seconds
+ // after the caller stops waiting, and the user was shown a red "ingestion
+ // failed" banner over work that had succeeded — then invited to redo a
+ // 35-60s job. A deadline must read as "still running", never as a failure.
+ mockedDrain.mockResolvedValue({
+ passes: 1,
+ sessionsProcessed: 3,
+ sessionsFailed: 0,
+ observations: 15,
+ remaining: 419,
+ moreRemaining: true,
+ timedOut: true,
+ });
+ const onToast = vi.fn();
+ renderWithProviders(<CodingSessionsCard onToast={onToast} />);
+
+ fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));
+
+ await waitFor(() =>
+ expect(onToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'info',
+ title: 'Import still running',
+ message: expect.stringContaining('Imported 3 sessions so far'),
+ })
+ )
+ );
+ // No error toast and no inline alert — both would tell the user the import
+ // is over when it is not.
+ expect(onToast).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ it('leads with the deadline when a stale failure count is also present', async () => {
+ // `sessionsFailed` carries the last *completed* pass's count, so on a
+ // timeout it describes superseded work. Reporting it would tell the user to
+ // retry a run that has not finished.
+ mockedDrain.mockResolvedValue({
+ passes: 2,
+ sessionsProcessed: 4,
+ sessionsFailed: 2,
+ observations: 9,
+ remaining: 100,
+ moreRemaining: true,
+ timedOut: true,
+ });
+ const onToast = vi.fn();
+ renderWithProviders(<CodingSessionsCard onToast={onToast} />);
+
+ fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));
+
+ await waitFor(() =>
+ expect(onToast).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'info', title: 'Import still running' })
+ )
+ );
+ expect(onToast).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'warning' }));
+ });
+
it('reports ingestion failures through the error toast', async () => {
mockedDrain.mockRejectedValue(new Error('persona pipeline failed'));
const onToast = vi.fn();
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index 717eadacd6..bca0afed3f 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -6656,6 +6656,9 @@ const messages: TranslationMap = {
'أنتجت {processed} جلسات {observations} ملاحظات شخصية.',
'memorySources.codingSessions.partialFailure':
'فشلت {failed} جلسات بينما تمت معالجة {processed}. شغّل الاستيعاب مرة أخرى لإعادة المحاولة.',
+ 'memorySources.codingSessions.stillRunning': 'الاستيراد ما زال جاريًا',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'تم استيراد {processed} جلسة حتى الآن. لم ينتهِ الاستيراد ضمن المهلة المحددة لكنه ما زال يعمل في الخلفية؛ تحقق مرة أخرى بعد دقيقة بدلًا من بدئه من جديد.',
'memorySources.codingSessions.failed': 'فشل استيعاب جلسات البرمجة',
'flows.canvas.sidePanelToggle': 'اللوحة الجانبية',
'flows.canvas.legendTab': 'يدوي',
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 32976d7cf9..eff8e979f5 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -6811,6 +6811,9 @@ const messages: TranslationMap = {
'{processed}টি সেশন থেকে {observations}টি পারসোনা পর্যবেক্ষণ তৈরি হয়েছে।',
'memorySources.codingSessions.partialFailure':
'{processed}টি সেশন প্রক্রিয়া করার সময় {failed}টি ব্যর্থ হয়েছে। আবার চেষ্টা করতে গ্রহণ পুনরায় চালান।',
+ 'memorySources.codingSessions.stillRunning': 'ইম্পোর্ট এখনও চলছে',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'এখন পর্যন্ত {processed}টি সেশন ইম্পোর্ট হয়েছে। নির্ধারিত সময়ের মধ্যে ইম্পোর্ট শেষ হয়নি, তবে সেটি ব্যাকগ্রাউন্ডে চলছে; আবার শুরু না করে এক মিনিট পরে দেখুন।',
'memorySources.codingSessions.failed': 'কোডিং সেশন গ্রহণ ব্যর্থ হয়েছে',
'flows.canvas.sidePanelToggle': 'সাইড প্যানেল',
'flows.canvas.legendTab': 'ম্যানুয়াল',
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 0b80332d3e..21fb43d122 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -6996,6 +6996,9 @@ const messages: TranslationMap = {
'{processed} Sitzungen ergaben {observations} Persona-Beobachtungen.',
'memorySources.codingSessions.partialFailure':
'{failed} Sitzungen sind fehlgeschlagen, während {processed} verarbeitet wurden. Starten Sie das Einlesen erneut.',
+ 'memorySources.codingSessions.stillRunning': 'Import läuft noch',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'Bisher wurden {processed} Sitzungen importiert. Der Import wurde nicht innerhalb seines Zeitbudgets fertig, läuft aber im Hintergrund weiter. Schauen Sie in einer Minute noch einmal nach, statt ihn neu zu starten.',
'memorySources.codingSessions.failed': 'Einlesen der Coding-Sitzungen fehlgeschlagen',
'flows.canvas.sidePanelToggle': 'Seitenleiste',
'flows.canvas.legendTab': 'Manuell',
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index 6aa539b0e5..9157ef82a8 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -7193,6 +7193,9 @@ const en: TranslationMap = {
'{processed} sessions produced {observations} persona observations.',
'memorySources.codingSessions.partialFailure':
'{failed} sessions failed while {processed} were processed. Run ingestion again to retry them.',
+ 'memorySources.codingSessions.stillRunning': 'Import still running',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'Imported {processed} sessions so far. The import did not finish inside its time budget but is still running in the background; check back in a minute rather than starting it again.',
'memorySources.codingSessions.failed': 'Coding-session ingestion failed',
'notifications.configRecovered.title': 'Settings file recovered',
'notifications.configRecovered.body':
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 5dcccc9c69..6febc23023 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -6954,6 +6954,9 @@ const messages: TranslationMap = {
'{processed} sesiones produjeron {observations} observaciones de personalidad.',
'memorySources.codingSessions.partialFailure':
'Fallaron {failed} sesiones mientras se procesaron {processed}. Ejecuta la ingesta de nuevo para reintentarlas.',
+ 'memorySources.codingSessions.stillRunning': 'La importación sigue en curso',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'Se han importado {processed} sesiones hasta ahora. La importación no terminó dentro de su tiempo asignado, pero sigue ejecutándose en segundo plano; vuelve a comprobarlo en un minuto en lugar de iniciarla otra vez.',
'memorySources.codingSessions.failed': 'Falló la ingesta de sesiones de programación',
'flows.canvas.sidePanelToggle': 'Panel lateral',
'flows.canvas.legendTab': 'Manual',
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index 419dd22fbe..97c30e94d9 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -6981,6 +6981,9 @@ const messages: TranslationMap = {
'{processed} sessions ont produit {observations} observations de persona.',
'memorySources.codingSessions.partialFailure':
'{failed} sessions ont échoué tandis que {processed} ont été traitées. Relancez l’ingestion pour réessayer.',
+ 'memorySources.codingSessions.stillRunning': 'Import toujours en cours',
+ 'memorySources.codingSessions.stillRunningMessage':
+ "{processed} sessions importées jusqu'ici. L'import n'a pas abouti dans le temps imparti mais continue en arrière-plan ; revenez dans une minute plutôt que de le relancer.",
'memorySources.codingSessions.failed': 'Échec de l’ingestion des sessions de programmation',
'flows.canvas.sidePanelToggle': 'Panneau latéral',
'flows.canvas.legendTab': 'Manuel',
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 215e79feca..ba57cb00cc 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -6807,6 +6807,9 @@ const messages: TranslationMap = {
'{processed} सत्रों से {observations} व्यक्तित्व अवलोकन बने।',
'memorySources.codingSessions.partialFailure':
'{processed} सत्र संसाधित हुए, जबकि {failed} विफल रहे। दोबारा प्रयास करने के लिए अंतर्ग्रहण फिर चलाएँ।',
+ 'memorySources.codingSessions.stillRunning': 'आयात अब भी चल रहा है',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'अब तक {processed} सत्र आयात हुए हैं। आयात अपनी समय सीमा में पूरा नहीं हुआ, लेकिन पृष्ठभूमि में चल रहा है; इसे दोबारा शुरू करने के बजाय एक मिनट बाद देखें।',
'memorySources.codingSessions.failed': 'कोडिंग सत्र शामिल करना विफल रहा',
'flows.canvas.sidePanelToggle': 'साइड पैनल',
'flows.canvas.legendTab': 'मैनुअल',
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index 1b9ae9c133..27ec8671a3 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -6842,6 +6842,9 @@ const messages: TranslationMap = {
'{processed} sesi menghasilkan {observations} pengamatan persona.',
'memorySources.codingSessions.partialFailure':
'{failed} sesi gagal sementara {processed} berhasil diproses. Jalankan penyerapan lagi untuk mencoba ulang.',
+ 'memorySources.codingSessions.stillRunning': 'Impor masih berjalan',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'Sejauh ini {processed} sesi telah diimpor. Impor belum selesai dalam batas waktunya tetapi masih berjalan di latar belakang; periksa lagi sebentar lagi daripada memulainya ulang.',
'memorySources.codingSessions.failed': 'Gagal menyerap sesi pemrograman',
'flows.canvas.sidePanelToggle': 'Panel samping',
'flows.canvas.legendTab': 'Manual',
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index 4ae1d61880..66ba6d2e3e 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -6937,6 +6937,9 @@ const messages: TranslationMap = {
'{processed} sessioni hanno prodotto {observations} osservazioni della persona.',
'memorySources.codingSessions.partialFailure':
'{failed} sessioni non sono riuscite mentre {processed} sono state elaborate. Avvia di nuovo l’acquisizione per riprovare.',
+ 'memorySources.codingSessions.stillRunning': 'Importazione ancora in corso',
+ 'memorySources.codingSessions.stillRunningMessage':
+ "Finora sono state importate {processed} sessioni. L'importazione non si è conclusa entro il tempo previsto ma prosegue in background; ricontrolla tra un minuto invece di avviarla di nuovo.",
'memorySources.codingSessions.failed':
'Acquisizione delle sessioni di programmazione non riuscita',
'flows.canvas.sidePanelToggle': 'Pannello laterale',
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index 6f7b53f250..28a4673069 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -6732,6 +6732,9 @@ const messages: TranslationMap = {
'세션 {processed}개에서 페르소나 관찰 {observations}개를 만들었습니다.',
'memorySources.codingSessions.partialFailure':
'세션 {processed}개를 처리하는 동안 {failed}개가 실패했습니다. 다시 시도하려면 수집을 다시 실행하세요.',
+ 'memorySources.codingSessions.stillRunning': '가져오기가 아직 진행 중입니다',
+ 'memorySources.codingSessions.stillRunningMessage':
+ '지금까지 {processed}개의 세션을 가져왔습니다. 제한 시간 안에 끝나지 않았지만 백그라운드에서 계속 실행 중입니다. 다시 시작하지 말고 잠시 후 확인하세요.',
'memorySources.codingSessions.failed': '코딩 세션 수집 실패',
'flows.canvas.sidePanelToggle': '사이드 패널',
'flows.canvas.legendTab': '수동',
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 0214ce62cd..104833f0ed 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -6908,6 +6908,9 @@ const messages: TranslationMap = {
'{processed} sesji utworzyło {observations} obserwacji persony.',
'memorySources.codingSessions.partialFailure':
'Nie udało się przetworzyć {failed} sesji, a {processed} przetworzono. Uruchom import ponownie, aby spróbować jeszcze raz.',
+ 'memorySources.codingSessions.stillRunning': 'Import wciąż trwa',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'Zaimportowano dotąd {processed} sesji. Import nie zakończył się w wyznaczonym czasie, ale nadal działa w tle; sprawdź ponownie za minutę, zamiast uruchamiać go od nowa.',
'memorySources.codingSessions.failed': 'Nie udało się wczytać sesji programistycznych',
'flows.canvas.sidePanelToggle': 'Panel boczny',
'flows.canvas.legendTab': 'Ręczny',
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index 6724826529..2be0ed5ecb 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -6921,6 +6921,9 @@ const messages: TranslationMap = {
'{processed} sessões produziram {observations} observações de persona.',
'memorySources.codingSessions.partialFailure':
'{failed} sessões falharam enquanto {processed} foram processadas. Execute a ingestão novamente para tentar de novo.',
+ 'memorySources.codingSessions.stillRunning': 'Importação ainda em andamento',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'Foram importadas {processed} sessões até agora. A importação não terminou dentro do tempo previsto, mas continua a ser executada em segundo plano; verifique novamente daqui a um minuto em vez de iniciá-la outra vez.',
'memorySources.codingSessions.failed': 'Falha ao ingerir sessões de programação',
'flows.canvas.sidePanelToggle': 'Painel lateral',
'flows.canvas.legendTab': 'Manual',
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index ef27432b74..6431275398 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -6882,6 +6882,9 @@ const messages: TranslationMap = {
'Обработано сеансов: {processed}; наблюдений персоны: {observations}.',
'memorySources.codingSessions.partialFailure':
'Не удалось обработать сеансов: {failed}; обработано: {processed}. Запустите загрузку ещё раз для повтора.',
+ 'memorySources.codingSessions.stillRunning': 'Импорт всё ещё выполняется',
+ 'memorySources.codingSessions.stillRunningMessage':
+ 'На данный момент импортировано сессий: {processed}. Импорт не завершился в отведённое время, но продолжает выполняться в фоновом режиме; загляните через минуту, а не запускайте его заново.',
'memorySources.codingSessions.failed': 'Не удалось загрузить сеансы программирования',
'flows.canvas.sidePanelToggle': 'Боковая панель',
'flows.canvas.legendTab': 'Вручную',
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index 5cc4c8e702..84ca3cac68 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -6441,6 +6441,9 @@ const messages: TranslationMap = {
'{processed} 个会话生成了 {observations} 条人格观察。',
'memorySources.codingSessions.partialFailure':
'{processed} 个会话已处理,{failed} 个失败。请再次运行摄取以重试。',
+ 'memorySources.codingSessions.stillRunning': '导入仍在进行中',
+ 'memorySources.codingSessions.stillRunningMessage':
+ '目前已导入 {processed} 个会话。导入未在限定时间内完成,但仍在后台运行;请稍后再查看,不要重新开始。',
'memorySources.codingSessions.failed': '编程会话摄取失败',
'flows.canvas.sidePanelToggle': '侧边栏',
'flows.canvas.legendTab': '手动',
diff --git a/app/src/services/memorySourcesService.test.ts b/app/src/services/memorySourcesService.test.ts
index 2ad168be44..79c1809ef1 100644
--- a/app/src/services/memorySourcesService.test.ts
+++ b/app/src/services/memorySourcesService.test.ts
@@ -8,6 +8,7 @@ import {
drainCodingSessions,
getCodingSessionStatus,
ingestCodingSessions,
+ isIngestTimeout,
listMemorySources,
type MemorySourceEntry,
removeMemorySource,
@@ -300,6 +301,52 @@ describe('memorySourcesService', () => {
expect(result.moreRemaining).toBe(true);
});
+ it('reports a deadline as still-running, not as a thrown failure', async () => {
+ // The #5802 shape: a pass completes, the next one trips a deadline. No
+ // deadline in this stack cancels the import, so the run is still going —
+ // rejecting here is what put a red "failed" banner over work that
+ // succeeded seconds later.
+ mockedCall
+ .mockResolvedValueOnce(ingestResult({ sessions_processed: 3, budget_hit: true }))
+ .mockRejectedValueOnce(
+ new Error('ingest coding sessions: call to `IngestCodingSessions` timed out after 30000ms')
+ );
+
+ const result = await drainCodingSessions();
+
+ expect(result.timedOut).toBe(true);
+ // The completed pass's work is kept: those sessions really were imported.
+ expect(result.sessionsProcessed).toBe(3);
+ expect(result.passes).toBe(1);
+ });
+
+ it('reports the core budget deadline too, which is spelled in seconds', async () => {
+ // `ingest_budget` renders "timed out after 570s". The seconds form does not
+ // match coreRpcClient's `\d+ms` timeout classifier, so a check that keyed
+ // only on CoreRpcError.kind would let this one through as a failure.
+ mockedCall.mockRejectedValueOnce(new Error('ingest coding sessions: timed out after 570s'));
+
+ const result = await drainCodingSessions();
+
+ expect(result.timedOut).toBe(true);
+ expect(result.sessionsProcessed).toBe(0);
+ });
+
+ it('still rejects a genuine ingest failure', async () => {
+ // The other half of the contract: making a deadline non-fatal must not make
+ // everything non-fatal.
+ mockedCall.mockRejectedValueOnce(new Error('persona pipeline failed'));
+
+ await expect(drainCodingSessions()).rejects.toThrow('persona pipeline failed');
+ });
+
+ it('isIngestTimeout does not treat an unrelated message as a deadline', () => {
+ expect(isIngestTimeout(new Error('the request timed out'))).toBe(false);
+ expect(isIngestTimeout(new Error('session scan failed'))).toBe(false);
+ expect(isIngestTimeout(new Error('timed out after 30000ms'))).toBe(true);
+ expect(isIngestTimeout(new Error('timed out after 570s'))).toBe(true);
+ });
+
it('stops when a budget-hit pass makes no forward progress', async () => {
// Backlog still reports budget_hit, but nothing new is distilled — avoid an
// infinite loop on sessions that only ever fail.
diff --git a/app/src/services/memorySourcesService.ts b/app/src/services/memorySourcesService.ts
index c33f5e8fbe..aa1ee7dce4 100644
--- a/app/src/services/memorySourcesService.ts
+++ b/app/src/services/memorySourcesService.ts
@@ -299,6 +299,50 @@ export interface CodingSessionDrainProgress {
remaining: number;
/** True while the backlog still reported more work after the latest pass. */
moreRemaining: boolean;
+ /**
+ * True when a pass stopped waiting on a deadline rather than failing.
+ *
+ * The distinction is the whole point: no deadline in this stack cancels the
+ * work it bounds. The core's `ingest_budget` and tinybus' call deadline both
+ * only release the *caller* — tinybus says so in as many words: *"A timeout
+ * does not cancel the remote work."* So the import is still running, its
+ * result is simply not going to arrive on this call, and reporting it as a
+ * failure is both wrong and harmful: it invites a retry of a 35-60 s job
+ * that already succeeded (#5802).
+ */
+ timedOut: boolean;
+}
+
+/**
+ * Whether a rejected ingest pass is a deadline rather than a failure.
+ *
+ * Three shapes reach here, and all three mean "stopped waiting", not "broke":
+ *
+ * - `CoreRpcError` with `kind === 'timeout'` — the client's own
+ * `AbortController` fired at `timeoutMs`.
+ * - `... timed out after 30000ms` — a tinybus call deadline, rendered by
+ * `vendor/tinybus/crates/tinybus/src/error.rs`. `classifyRpcError` already
+ * maps this to `'timeout'`, but it is matched here too so the check does not
+ * depend on a `CoreRpcError` reaching this frame intact.
+ * - `ingest coding sessions: timed out after 570s` — the core's own
+ * `ingest_budget` ceiling (`memory/sources/rpc.rs`). Note the unit: this one
+ * is **seconds**, so it does not match `classifyRpcError`'s `\d+ms` arm and
+ * is classified `'transport'`. Only the message catches it.
+ *
+ * The kind is read structurally rather than through `instanceof CoreRpcError`.
+ * A class identity is the wrong thing to hang this on: it is one bundling
+ * decision or one partially-mocked module away from silently answering `false`
+ * and putting the failure banner back — which is exactly what a unit test
+ * mocking `coreRpcClient` reproduces.
+ *
+ * A false positive here would hide a real failure, so the pattern stays
+ * anchored on the literal phrase both layers emit rather than on a bare
+ * "timeout" anywhere in the text.
+ */
+export function isIngestTimeout(cause: unknown): boolean {
+ if ((cause as { kind?: unknown } | null)?.kind === 'timeout') return true;
+ const message = cause instanceof Error ? cause.message : String(cause);
+ return /timed out after \d+\s*(ms|s)\b/i.test(message);
}
export interface CodingSessionDrainOptions {
@@ -342,6 +386,7 @@ export async function drainCodingSessions(
observations: 0,
remaining: 0,
moreRemaining: false,
+ timedOut: false,
};
log('drain_coding_sessions: entry max_per_pass=%d max_passes=%d', maxSessionsPerPass, maxPasses);
@@ -350,7 +395,26 @@ export async function drainCodingSessions(
log('drain_coding_sessions: stop requested after pass=%d', progress.passes);
break;
}
- const result = await ingestCodingSessions(false, maxSessionsPerPass);
+ let result: CodingSessionIngestResult;
+ try {
+ result = await ingestCodingSessions(false, maxSessionsPerPass);
+ } catch (cause) {
+ // A deadline is not a failure. Nothing in this stack cancels the import
+ // when a caller stops waiting for it, so the pass is still running and
+ // will still write its observations — it just has no report to hand back
+ // on this call. Rethrowing here is what put a red "ingestion failed"
+ // banner over a run that went on to succeed, and invited the user to
+ // redo 35-60 s of work (#5802).
+ //
+ // Returning rather than rethrowing keeps every completed pass's counts,
+ // which is the honest answer: those passes really did import what they
+ // report, and only the last one is unresolved.
+ if (!isIngestTimeout(cause)) throw cause;
+ progress.timedOut = true;
+ log('drain_coding_sessions: pass=%d timed out; work continues', progress.passes + 1);
+ onProgress?.({ ...progress });
+ break;
+ }
progress.passes += 1;
progress.sessionsProcessed += result.sessions_processed;
progress.sessionsFailed = result.sessions_failed;
diff --git a/src/openhuman/memory/sources/rpc.rs b/src/openhuman/memory/sources/rpc.rs
index aff92aeb47..5c6f158de2 100644
--- a/src/openhuman/memory/sources/rpc.rs
+++ b/src/openhuman/memory/sources/rpc.rs
@@ -177,7 +177,13 @@ pub async fn coding_session_status_rpc() -> Result<RpcOutcome<CodingSessionStatu
/// server budget the *tighter* of the two so it returns a clean structured
/// timeout before the client's fetch aborts. This is a *ceiling to catch a wedged
/// run*, not a latency target.
-fn ingest_budget(max_sessions: usize) -> std::time::Duration {
+///
+/// `pub(crate)` so the module driver can size its own bus deadline from the
+/// same formula (`modules::memory`). That call sits *inside* this one, and
+/// tinybus gives every call a 30 s default deadline if nobody sets one — 19×
+/// tighter than the smallest budget computed here, which is how a completed
+/// import came to be reported as a failure (#5802). One formula, two layers.
+pub(crate) fn ingest_budget(max_sessions: usize) -> std::time::Duration {
/// Fixed overhead allowance (config load, discovery, process warm-up) added
/// on top of the per-session budget.
const BASE_SECS: u64 = 120;
diff --git a/src/openhuman/modules/memory.rs b/src/openhuman/modules/memory.rs
index 83844eb047..e91bbfbfe5 100644
--- a/src/openhuman/modules/memory.rs
+++ b/src/openhuman/modules/memory.rs
@@ -1159,19 +1159,60 @@ impl MemoryCodingSessions for ModuleMemoryProvider {
async fn coding_session_status(&self) -> Result<Vec<CodingSessionSource>, MemoryError> {
module_call!(self, "coding_session_status", "CodingSessionStatus", ())
}
+ /// # Why this one call sets its own bus deadline
+ ///
+ /// Every other member here takes tinybus' `DEFAULT_TIMEOUT`
+ /// (`vendor/tinybus/crates/tinybus/src/connection.rs:56`) — a flat 30 s,
+ /// applied by `Proxy::new` (`proxy.rs:59`) whenever nobody says otherwise.
+ /// That is the right default for a memory read. It is the wrong one here:
+ /// distilling a coding session is several *sequential* model calls, and the
+ /// RPC above it already computes a budget sized to the work
+ /// (`memory::sources::rpc::ingest_budget`, 120 s + 90 s per session, capped
+ /// at 600 s).
+ ///
+ /// So there were two deadlines and the tighter one was the one nobody
+ /// chose. A real 35 s import tripped the 30 s default; the caller was
+ /// released with an error while the module kept working and finished
+ /// seconds later, having imported everything. The UI reported a failure for
+ /// work that had succeeded, and invited a retry that would redo it
+ /// (#5802).
+ ///
+ /// tinybus is explicit that this is the caller's problem to size: *"A
+ /// timeout does not cancel the remote work — tinybus cannot — it stops
+ /// waiting and frees the caller"* (`connection.rs:22-23`). Abandoning the
+ /// call early therefore does not save anything; it only loses the report.
+ ///
+ /// The budget is taken from `ingest_budget` rather than restated, so the
+ /// two layers cannot drift, plus [`INGEST_BUS_GRACE`]. The grace makes the
+ /// ordering deterministic instead of a race between two equal deadlines:
+ /// the RPC's own `tokio::time::timeout` fires first and reports its clean
+ /// structured message, and this deadline survives only as the
+ /// wedged-forever backstop tinybus requires. Same shape as the client's
+ /// `CODING_SESSION_RPC_GRACE_MS` sitting above the server budget.
async fn ingest_coding_sessions(
&self,
request: CodingSessionIngestRequest,
) -> Result<CodingSessionIngestReport, MemoryError> {
- module_call!(
- self,
- "ingest_coding_sessions",
- "IngestCodingSessions",
- (request,)
- )
+ let deadline = crate::openhuman::memory::sources::rpc::ingest_budget(request.max_sessions)
+ + INGEST_BUS_GRACE;
+ self.proxy("ingest_coding_sessions")
+ .await?
+ .with_timeout(deadline)
+ .call("IngestCodingSessions", (request,))
+ .await
+ .map_err(|error| from_bus(&error))
}
}
+/// Head-room added to [`ingest_budget`](crate::openhuman::memory::sources::rpc::ingest_budget)
+/// for the bus deadline on `IngestCodingSessions`.
+///
+/// Exists to order two deadlines, not to allow more work: the RPC's own
+/// wall-clock ceiling must be the one that fires, because its message names the
+/// budget rather than the wire member. Anything comfortably longer than the
+/// scheduling jitter between the two `tokio::time::timeout` arms would do.
+const INGEST_BUS_GRACE: std::time::Duration = std::time::Duration::from_secs(30);
+
#[async_trait]
impl MemoryEpisodic for ModuleMemoryProvider {
async fn insert_turn(&self, turn: &EpisodicTurn) -> Result<i64, MemoryError> {
diff --git a/src/openhuman/modules/memory_tests.rs b/src/openhuman/modules/memory_tests.rs
index dbaf69545c..0713121eeb 100644
--- a/src/openhuman/modules/memory_tests.rs
+++ b/src/openhuman/modules/memory_tests.rs
@@ -13,7 +13,7 @@ use tinymemory_api::capabilities::{Capabilities, Capability};
use tinymemory_api::error::MemoryError;
use tinymemory_api::provider::MemoryProvider;
-use super::{from_bus, ModuleMemoryProvider, MODULE_ID};
+use super::{from_bus, ModuleMemoryProvider, INGEST_BUS_GRACE, MODULE_ID};
use crate::openhuman::config::Config;
use crate::openhuman::modules::registry;
@@ -369,3 +369,48 @@ fn the_ci_workflows_pin_the_same_module_digest_as_the_registry() {
guard silently stopped checking anything"
);
}
+
+/// The bus deadline on `IngestCodingSessions` must never be the one that fires.
+///
+/// This is the defect from #5802 in test form. Before the fix the module call
+/// took tinybus' flat 30 s `DEFAULT_TIMEOUT` while the RPC around it allowed
+/// 120 s + 90 s per session, so a perfectly healthy 35 s import was abandoned
+/// by the caller, reported as a failure, and finished successfully five
+/// seconds later with nobody listening.
+///
+/// Asserted across the whole input range rather than at one point, because the
+/// budget is piecewise: it scales linearly and then clamps at `HARD_CAP_SECS`.
+/// A future edit that raises the cap, the base, or the per-session allowance
+/// without touching the grace fails here instead of in the field.
+#[test]
+fn the_ingest_bus_deadline_always_outlasts_the_rpc_budget() {
+ use crate::openhuman::memory::sources::rpc::ingest_budget;
+
+ // Below the cap, at the cap, and far past it (`max_sessions` is untrusted
+ // input from an advertised RPC, so `usize::MAX` is a reachable argument).
+ for max_sessions in [0, 1, 5, 6, 7, 100, 10_000, usize::MAX] {
+ let budget = ingest_budget(max_sessions);
+ let bus = budget + INGEST_BUS_GRACE;
+ assert!(
+ bus > budget,
+ "max_sessions={max_sessions}: the bus deadline ({bus:?}) must outlast the \
+ RPC budget ({budget:?}), or the wire member's error wins and the caller \
+ is released while the module is still working"
+ );
+ }
+}
+
+/// The grace has to be big enough to order two timers, not merely non-zero.
+///
+/// A one-millisecond grace would satisfy the assertion above and still lose the
+/// race under ordinary scheduling jitter, which would put the failure back
+/// where it started: a bus-member error surfacing instead of the RPC's
+/// structured one.
+#[test]
+fn the_ingest_bus_grace_is_wide_enough_to_order_the_two_timers() {
+ assert!(
+ INGEST_BUS_GRACE >= std::time::Duration::from_secs(5),
+ "INGEST_BUS_GRACE is {INGEST_BUS_GRACE:?}; a grace this small does not \
+ reliably order the RPC's timeout ahead of the bus deadline"
+ );
+}