Skip to content

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

fix(composio): keep the single-call sync budget at 500 across 200-item passes

Shanuaba2ad7ce1d8
diff --git a/app/src/components/intelligence/MemorySourceRow.pipelineWarning.test.tsx b/app/src/components/intelligence/MemorySourceRow.pipelineWarning.test.tsx
index c3115c7faa..e5c06d8410 100644
--- a/app/src/components/intelligence/MemorySourceRow.pipelineWarning.test.tsx
+++ b/app/src/components/intelligence/MemorySourceRow.pipelineWarning.test.tsx
@@ -30,7 +30,7 @@ import { MemorySourceRow } from './MemorySourceRow';
vi.mock('../../lib/i18n/I18nContext', () => ({
useT: () => ({
t: (k: string) =>
- k === 'sync.pipeline.vectorsPending' ? '{count} chunks waiting for vectors' : k,
+ k === 'sync.pipeline.vectorsPending' ? 'Chunks waiting for vectors: {count}' : k,
}),
}));
@@ -226,7 +226,7 @@ describe('MemorySourceRow — a backlog that is still draining is pending, not f
expect(warning()).not.toBeInTheDocument();
const note = pendingNote();
expect(note).toBeInTheDocument();
- expect(note).toHaveTextContent('322 chunks waiting for vectors');
+ expect(note).toHaveTextContent('Chunks waiting for vectors: 322');
// The freshness pill stays; the amber "Ingested only" pill does not appear.
expect(screen.getByText('sync.idle')).toBeInTheDocument();
expect(
diff --git a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.test.tsx b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.test.tsx
index 3437c5a8f4..11ee5b4678 100644
--- a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.test.tsx
+++ b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.test.tsx
@@ -175,7 +175,7 @@ describe('MemorySourcesRegistry', () => {
renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);
const note = await screen.findByTestId('memory-source-vectors-pending-src_1');
- expect(note).toHaveTextContent('4 chunks waiting for vectors');
+ expect(note).toHaveTextContent('Chunks waiting for vectors: 4');
expect(screen.queryByTestId('memory-source-pipeline-warning-src_1')).not.toBeInTheDocument();
expect(mockedBackfill).toHaveBeenCalled();
});
diff --git a/app/src/components/intelligence/sourcePipelineStatus.ts b/app/src/components/intelligence/sourcePipelineStatus.ts
index 1cc02e4c8b..ba4a998911 100644
--- a/app/src/components/intelligence/sourcePipelineStatus.ts
+++ b/app/src/components/intelligence/sourcePipelineStatus.ts
@@ -127,6 +127,13 @@ export function deriveSourcePipelineHealth(
// chain with rows to process, OR this source's newest chunk landed inside
// the core's own `recent` window (≤ 5 min: ingest is still writing and
// the chain is queued behind it). A backlog with neither is stuck: hard.
+ //
+ // `backfill.in_progress` is process-wide on purpose, not a per-source
+ // signal to be narrowed: the chain it reports is signature-wide — each
+ // batch takes any chunk lacking a vector at the active signature, whoever
+ // ingested it — so a running chain is draining THIS source's backlog too.
+ // (A chunk the chain skipped for good is tombstoned and no longer counts as
+ // pending, so it cannot hide behind the flag.)
const pending = status?.chunks_pending ?? 0;
const recallLatched = degraded?.semantic_recall === true;
const embeddingsBlocked = causeCode !== null && EMBEDDINGS_BLOCKING_CAUSES.has(causeCode);
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index ead3312491..59be791501 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -6479,7 +6479,8 @@ const messages: TranslationMap = {
// Data Sync layered pipeline status (GH-4690)
'sync.pipeline.ingestedOnly': 'تم الاستيعاب فقط',
'sync.pipeline.storedWithoutVectors': 'مخزَّن بدون متجهات. البحث الدلالي غير متاح.',
- 'sync.pipeline.vectorsPending': '{count} أجزاء في انتظار المتجهات. سيشملها البحث الدلالي قريبًا.',
+ 'sync.pipeline.vectorsPending':
+ 'أجزاء في انتظار المتجهات: {count}. سيشملها البحث الدلالي قريبًا.',
'sync.pipeline.signInToEnable': 'سجّل الدخول للتفعيل',
'sync.pipeline.extractionFailed': 'فشل استخراج بنية الذاكرة. قد يكون الويكي غير مكتمل.',
'sync.pipeline.treeDegraded': 'شجرة الذاكرة متدهورة. قد يُرجع الاسترجاع نتائج قديمة.',
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index a185e7a015..da3aef9cf4 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -6632,7 +6632,7 @@ const messages: TranslationMap = {
'sync.pipeline.ingestedOnly': 'শুধু গৃহীত',
'sync.pipeline.storedWithoutVectors': 'ভেক্টর ছাড়াই সংরক্ষিত। শব্দার্থিক অনুসন্ধান অনুপলব্ধ।',
'sync.pipeline.vectorsPending':
- '{count}টি চাংক ভেক্টরের জন্য অপেক্ষা করছে। শব্দার্থিক অনুসন্ধান শীঘ্রই সেগুলি অন্তর্ভুক্ত করবে।',
+ 'ভেক্টরের জন্য অপেক্ষমাণ চাংক: {count}। শব্দার্থিক অনুসন্ধান শীঘ্রই সেগুলি অন্তর্ভুক্ত করবে।',
'sync.pipeline.signInToEnable': 'সক্রিয় করতে সাইন ইন করুন',
'sync.pipeline.extractionFailed': 'মেমরি কাঠামো নিষ্কাশন ব্যর্থ হয়েছে। উইকি অসম্পূর্ণ হতে পারে।',
'sync.pipeline.treeDegraded': 'মেমরি ট্রি অবনমিত। পুনরুদ্ধার পুরনো ফলাফল দিতে পারে।',
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index bf5f54e259..1217a05446 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -6819,7 +6819,7 @@ const messages: TranslationMap = {
'sync.pipeline.storedWithoutVectors':
'Ohne Vektoren gespeichert. Semantische Suche nicht verfügbar.',
'sync.pipeline.vectorsPending':
- '{count} Brocken warten auf Vektoren. Die semantische Suche deckt sie in Kürze ab.',
+ 'Brocken, die auf Vektoren warten: {count}. Die semantische Suche deckt sie in Kürze ab.',
'sync.pipeline.signInToEnable': 'Zum Aktivieren anmelden',
'sync.pipeline.extractionFailed':
'Extraktion der Speicherstruktur fehlgeschlagen. Das Wiki ist möglicherweise unvollständig.',
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index ec91a82fb0..9bf999c696 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -2953,7 +2953,7 @@ const en: TranslationMap = {
'sync.pipeline.ingestedOnly': 'Ingested only',
'sync.pipeline.storedWithoutVectors': 'Stored without vectors. Semantic search unavailable.',
'sync.pipeline.vectorsPending':
- '{count} chunks waiting for vectors. Semantic search will cover them shortly.',
+ 'Chunks waiting for vectors: {count}. Semantic search will cover them shortly.',
'sync.pipeline.signInToEnable': 'Sign in to enable',
'sync.pipeline.extractionFailed': 'Memory structure extraction failed. Wiki may be incomplete.',
'sync.pipeline.treeDegraded': 'Memory tree degraded. Retrieval may return stale results.',
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 6d952c0622..99e4f7cc3f 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -6778,7 +6778,7 @@ const messages: TranslationMap = {
'sync.pipeline.storedWithoutVectors':
'Almacenado sin vectores. La búsqueda semántica no está disponible.',
'sync.pipeline.vectorsPending':
- '{count} fragmentos esperan vectores. La búsqueda semántica los cubrirá en breve.',
+ 'Fragmentos en espera de vectores: {count}. La búsqueda semántica los cubrirá en breve.',
'sync.pipeline.signInToEnable': 'Inicia sesión para activar',
'sync.pipeline.extractionFailed':
'Error al extraer la estructura de memoria. Es posible que el wiki esté incompleto.',
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index 2ac975d42e..7ef759672a 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -6805,7 +6805,7 @@ const messages: TranslationMap = {
'sync.pipeline.storedWithoutVectors':
'Enregistré sans vecteurs. Recherche sémantique indisponible.',
'sync.pipeline.vectorsPending':
- '{count} segments attendent leurs vecteurs. La recherche sémantique les couvrira sous peu.',
+ 'Segments en attente de vecteurs : {count}. La recherche sémantique les couvrira sous peu.',
'sync.pipeline.signInToEnable': 'Connectez-vous pour activer',
'sync.pipeline.extractionFailed':
"Échec de l'extraction de la structure mémoire. Le wiki peut être incomplet.",
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 99fb9bcf07..bdb0b5fe1e 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -6631,7 +6631,7 @@ const messages: TranslationMap = {
'sync.pipeline.ingestedOnly': 'केवल अंतर्ग्रहीत',
'sync.pipeline.storedWithoutVectors': 'वेक्टर के बिना संग्रहीत। सिमेंटिक खोज अनुपलब्ध।',
'sync.pipeline.vectorsPending':
- '{count} चंक्स वेक्टर की प्रतीक्षा में हैं। सिमेंटिक खोज जल्द ही उन्हें शामिल करेगी।',
+ 'वेक्टर की प्रतीक्षा में चंक्स: {count}। सिमेंटिक खोज जल्द ही उन्हें शामिल करेगी।',
'sync.pipeline.signInToEnable': 'सक्षम करने के लिए साइन इन करें',
'sync.pipeline.extractionFailed': 'मेमोरी संरचना निष्कर्षण विफल रहा। विकी अपूर्ण हो सकता है।',
'sync.pipeline.treeDegraded': 'मेमोरी ट्री अवक्रमित। पुनर्प्राप्ति पुराने परिणाम दे सकती है।',
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index 54f12edcd5..48223a9f54 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -6667,7 +6667,7 @@ const messages: TranslationMap = {
'sync.pipeline.ingestedOnly': 'Hanya diserap',
'sync.pipeline.storedWithoutVectors': 'Disimpan tanpa vektor. Pencarian semantik tidak tersedia.',
'sync.pipeline.vectorsPending':
- '{count} chunk menunggu vektor. Pencarian semantik akan segera mencakupnya.',
+ 'Chunk yang menunggu vektor: {count}. Pencarian semantik akan segera mencakupnya.',
'sync.pipeline.signInToEnable': 'Masuk untuk mengaktifkan',
'sync.pipeline.extractionFailed': 'Ekstraksi struktur memori gagal. Wiki mungkin tidak lengkap.',
'sync.pipeline.treeDegraded':
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index 62e49fa9d6..60eeadcb42 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -6760,7 +6760,7 @@ const messages: TranslationMap = {
'sync.pipeline.storedWithoutVectors':
'Memorizzato senza vettori. Ricerca semantica non disponibile.',
'sync.pipeline.vectorsPending':
- '{count} chunk in attesa dei vettori. La ricerca semantica li coprirà a breve.',
+ 'Chunk in attesa dei vettori: {count}. La ricerca semantica li coprirà a breve.',
'sync.pipeline.signInToEnable': 'Accedi per attivare',
'sync.pipeline.extractionFailed':
'Estrazione della struttura della memoria non riuscita. Il wiki potrebbe essere incompleto.',
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index 2370af617c..2fcf4bf48a 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -6556,8 +6556,7 @@ const messages: TranslationMap = {
// Data Sync layered pipeline status (GH-4690)
'sync.pipeline.ingestedOnly': '수집만 완료',
'sync.pipeline.storedWithoutVectors': '벡터 없이 저장됨. 의미 검색을 사용할 수 없습니다.',
- 'sync.pipeline.vectorsPending':
- '{count}개 청크가 벡터를 기다리는 중입니다. 곧 시맨틱 검색에 포함됩니다.',
+ 'sync.pipeline.vectorsPending': '벡터를 기다리는 청크: {count}개. 곧 시맨틱 검색에 포함됩니다.',
'sync.pipeline.signInToEnable': '사용하려면 로그인하세요',
'sync.pipeline.extractionFailed': '메모리 구조 추출에 실패했습니다. 위키가 불완전할 수 있습니다.',
'sync.pipeline.treeDegraded':
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 12527a1e6d..c127debd7a 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -6736,7 +6736,7 @@ const messages: TranslationMap = {
'sync.pipeline.storedWithoutVectors':
'Zapisano bez wektorów. Wyszukiwanie semantyczne niedostępne.',
'sync.pipeline.vectorsPending':
- '{count} fragmentów czeka na wektory. Wyszukiwanie semantyczne wkrótce je obejmie.',
+ 'Fragmenty oczekujące na wektory: {count}. Wyszukiwanie semantyczne wkrótce je obejmie.',
'sync.pipeline.signInToEnable': 'Zaloguj się, aby włączyć',
'sync.pipeline.extractionFailed':
'Ekstrakcja struktury pamięci nie powiodła się. Wiki może być niekompletne.',
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index 7e607625a7..e474ea700d 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -6746,7 +6746,7 @@ const messages: TranslationMap = {
'sync.pipeline.ingestedOnly': 'Apenas ingerido',
'sync.pipeline.storedWithoutVectors': 'Armazenado sem vetores. Pesquisa semântica indisponível.',
'sync.pipeline.vectorsPending':
- '{count} blocos aguardam vetores. A pesquisa semântica irá abrangê-los em breve.',
+ 'Blocos a aguardar vetores: {count}. A pesquisa semântica irá abrangê-los em breve.',
'sync.pipeline.signInToEnable': 'Inicie sessão para ativar',
'sync.pipeline.extractionFailed':
'Falha na extração da estrutura de memória. O wiki pode estar incompleto.',
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index ec0e67769d..fd06df383e 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -6707,7 +6707,7 @@ const messages: TranslationMap = {
'sync.pipeline.ingestedOnly': 'Только загружено',
'sync.pipeline.storedWithoutVectors': 'Сохранено без векторов. Семантический поиск недоступен.',
'sync.pipeline.vectorsPending':
- '{count} блоков ожидают векторы. Семантический поиск скоро охватит их.',
+ 'Блоков в ожидании векторов: {count}. Семантический поиск скоро охватит их.',
'sync.pipeline.signInToEnable': 'Войдите, чтобы включить',
'sync.pipeline.extractionFailed':
'Не удалось извлечь структуру памяти. Вики может быть неполной.',
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index 7800fffd30..8e91a24c38 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -6265,7 +6265,7 @@ const messages: TranslationMap = {
// Data Sync layered pipeline status (GH-4690)
'sync.pipeline.ingestedOnly': '仅已导入',
'sync.pipeline.storedWithoutVectors': '已存储但无向量。语义搜索不可用。',
- 'sync.pipeline.vectorsPending': '{count} 个片段正在等待向量。语义搜索很快会覆盖它们。',
+ 'sync.pipeline.vectorsPending': '等待向量的片段:{count} 个。语义搜索很快会覆盖它们。',
'sync.pipeline.signInToEnable': '登录以启用',
'sync.pipeline.extractionFailed': '记忆结构提取失败。维基可能不完整。',
'sync.pipeline.treeDegraded': '记忆树已降级。检索可能返回过时的结果。',
diff --git a/app/test/playwright/specs/brain-embedding-truthfulness.spec.ts b/app/test/playwright/specs/brain-embedding-truthfulness.spec.ts
index 487b107017..f09669104f 100644
--- a/app/test/playwright/specs/brain-embedding-truthfulness.spec.ts
+++ b/app/test/playwright/specs/brain-embedding-truthfulness.spec.ts
@@ -283,10 +283,24 @@ test.describe('Brain — the UI tells the truth about embedding state', () => {
// the truthful state is "waiting", and the row must say so rather than
// show a clean freshness pill and nothing else (openhuman#6025). It must
// equally not cry failure over work that is in flight.
- await expect(row.getByTestId(`memory-source-vectors-pending-${id}`)).toBeVisible({
- timeout: 30_000,
- });
- await expect(row).toContainText('waiting for vectors');
+ //
+ // The backlog can finish draining between the RPC read above and the
+ // row's next 5 s poll, so the expectation is decided at the assertion
+ // point from the core's own count: while chunks are still pending the
+ // note must be showing; once the count reaches zero the row is clean
+ // and the note is correctly gone. Only "pending but no note" is a
+ // failure, and it is polled past because the row refreshes on a timer.
+ const note = row.getByTestId(`memory-source-vectors-pending-${id}`);
+ await expect
+ .poll(
+ async () => {
+ const pendingNow = (await statusFor(id))?.chunks_pending ?? 0;
+ if (pendingNow === 0) return 'drained';
+ return (await note.isVisible()) ? 'pending-shown' : 'pending-hidden';
+ },
+ { timeout: 30_000, message: 'chunks are pending but the row shows no waiting note' }
+ )
+ .not.toBe('pending-hidden');
await expect(row).not.toContainText('Stored without vectors');
}
});
diff --git a/src/openhuman/integrations/composio/ops/mod.rs b/src/openhuman/integrations/composio/ops/mod.rs
index cb16fcf708..f9532a46fa 100644
--- a/src/openhuman/integrations/composio/ops/mod.rs
+++ b/src/openhuman/integrations/composio/ops/mod.rs
@@ -28,6 +28,7 @@ mod direct_mode;
mod error_utils;
mod execute;
mod memory_cleanup;
+mod pass_budget;
mod providers_ops;
mod toolkits;
mod tools_ops;
@@ -49,9 +50,11 @@ pub use providers_ops::{
composio_get_user_profile, composio_refresh_all_identities, composio_sync,
composio_sync_budgeted, composio_sync_for_source, RefreshIdentitiesReport, SYNC_PASS_MAX_ITEMS,
};
-// The tinyconnectors-mediated sync pass, shared with
-// `memory::sync::composio::providers::slack::rpc` — see its doc comment.
-pub(crate) use providers_ops::run_sync_pass;
+// The tinyconnectors-mediated sync pass, repeated within one call's item
+// budget for the entry points that sync once per invocation (periodic tick,
+// manual provider sync, `connection_created`, the Slack ingest RPC) — see
+// `pass_budget`'s doc comment.
+pub(crate) use pass_budget::run_sync_within_budget;
pub use toolkits::{
composio_list_agent_ready_toolkits, composio_list_capabilities, composio_list_toolkits,
};
diff --git a/src/openhuman/integrations/composio/ops/pass_budget.rs b/src/openhuman/integrations/composio/ops/pass_budget.rs
new file mode 100644
index 0000000000..0aee0602cc
--- /dev/null
+++ b/src/openhuman/integrations/composio/ops/pass_budget.rs
@@ -0,0 +1,101 @@
+//! Drain a connection within one invocation's item budget, one bounded pass
+//! at a time (openhuman#6025).
+//!
+//! `SYNC_PASS_MAX_ITEMS` dropped from 500 to 200 so that a single
+//! `AcceptSourceItems` call fits the host's 15-minute deadline. The entry
+//! points that make one sync call per invocation — the periodic tick, the
+//! manual provider sync, the `connection_created` initial sync and the Slack
+//! ingest RPC — used to hand the whole 500 to that one pass. Handing them 200
+//! would stop an account with 201–500 records short and still report the run
+//! complete (Codex review finding on #6026). So they keep the per-invocation
+//! budget they had, and spend it in passes the deadline can hold: each pass
+//! is sized by [`next_pass_budget`], and the loop ends when the connector
+//! reports the end or the budget is spent.
+
+use std::future::Future;
+
+use super::providers_ops::{next_pass_budget, run_sync_pass, SyncPassOutcome};
+use crate::openhuman::config::Config;
+
+/// Records one single-call entry point may read per invocation — the ceiling
+/// those callers had when a pass was 500 items. Read, not written: the old
+/// call's budget was what the module fetched, and a record the driver already
+/// held still spent it. The Sources-row button is not bound by this: it loops
+/// `composio_sync_budgeted` under its own cap.
+pub(crate) const SINGLE_CALL_ITEM_BUDGET: u32 = 500;
+
+/// Passes one call may make before it stops regardless — the same bound the
+/// Sources-row loop uses. Unreachable with full pages (three passes spend the
+/// budget); it exists so a module that keeps answering "more pending" with a
+/// trickle cannot pin the caller.
+const SINGLE_CALL_MAX_PASSES: usize = 50;
+
+/// Run passes until the connector reports the end, `budget` records have been
+/// read, a pass reads nothing, or [`SINGLE_CALL_MAX_PASSES`] is reached; each
+/// pass is capped at `SYNC_PASS_MAX_ITEMS` through [`next_pass_budget`].
+///
+/// The outcome sums `records_read` and `written` across passes, is
+/// `already_ingested` only when every pass was a no-op, and carries the last
+/// pass's `more_pending` and `message` — the same "last pass's word wins" rule
+/// the Sources-row loop applies. A pass error ends the run with that error;
+/// what earlier passes wrote is already committed by the driver.
+pub(crate) async fn run_passes_within_budget<F, Fut>(
+ budget: u32,
+ mut run_pass: F,
+) -> Result<SyncPassOutcome, String>
+where
+ F: FnMut(usize) -> Fut,
+ Fut: Future<Output = Result<SyncPassOutcome, String>>,
+{
+ let mut total = SyncPassOutcome {
+ already_ingested: true,
+ ..SyncPassOutcome::default()
+ };
+ let mut read: u64 = 0;
+ let mut passes = 0usize;
+ while let Some(pass_budget) = next_pass_budget(Some(budget), read) {
+ if passes >= SINGLE_CALL_MAX_PASSES {
+ break;
+ }
+ let pass = run_pass(pass_budget).await?;
+ passes += 1;
+ read = read.saturating_add(u64::try_from(pass.records_read).unwrap_or(u64::MAX));
+ total.records_read = total.records_read.saturating_add(pass.records_read);
+ total.written = total.written.saturating_add(pass.written);
+ total.already_ingested = total.already_ingested && pass.already_ingested;
+ total.more_pending = pass.more_pending;
+ total.message = pass.message;
+ // A pass that read nothing cannot make progress; "more pending" from
+ // it would only be asked again for the same nothing.
+ if !pass.more_pending || pass.records_read == 0 {
+ break;
+ }
+ }
+ if passes > 1 {
+ tracing::debug!(
+ passes,
+ written = total.written,
+ more_pending = total.more_pending,
+ "[composio] single-call sync spent its budget across passes"
+ );
+ }
+ Ok(total)
+}
+
+/// [`run_sync_pass`] for the single-call entry points: the same
+/// tinyconnectors-mediated pass, repeated within [`SINGLE_CALL_ITEM_BUDGET`].
+pub(crate) async fn run_sync_within_budget(
+ config: &Config,
+ toolkit: &str,
+ connection_id: &str,
+ reason: &str,
+) -> Result<SyncPassOutcome, String> {
+ run_passes_within_budget(SINGLE_CALL_ITEM_BUDGET, |pass_budget| {
+ run_sync_pass(config, toolkit, connection_id, reason, pass_budget)
+ })
+ .await
+}
+
+#[cfg(test)]
+#[path = "pass_budget_tests.rs"]
+mod tests;
diff --git a/src/openhuman/integrations/composio/ops/pass_budget_tests.rs b/src/openhuman/integrations/composio/ops/pass_budget_tests.rs
new file mode 100644
index 0000000000..f46c3adab2
--- /dev/null
+++ b/src/openhuman/integrations/composio/ops/pass_budget_tests.rs
@@ -0,0 +1,211 @@
+//! The budgeted drain the single-call sync entry points run (openhuman#6025).
+//!
+//! Scripted passes stand in for the connector: each test says what the
+//! module would return per call and asserts which pass budgets were asked for
+//! and what the aggregate reports.
+
+use std::cell::RefCell;
+use std::collections::VecDeque;
+
+use super::super::providers_ops::{SyncPassOutcome, SYNC_PASS_MAX_ITEMS};
+use super::{run_passes_within_budget, SINGLE_CALL_ITEM_BUDGET};
+
+fn pass(written: u32, more_pending: bool) -> SyncPassOutcome {
+ SyncPassOutcome {
+ records_read: written as usize,
+ written,
+ already_ingested: false,
+ more_pending,
+ message: None,
+ }
+}
+
+/// Drive the loop with a scripted connector; returns the outcome and the
+/// per-pass budgets it asked for, in order.
+async fn drive(
+ budget: u32,
+ script: Vec<Result<SyncPassOutcome, String>>,
+) -> (Result<SyncPassOutcome, String>, Vec<usize>) {
+ let script = RefCell::new(VecDeque::from(script));
+ let asked = RefCell::new(Vec::new());
+ let out = run_passes_within_budget(budget, |pass_budget| {
+ asked.borrow_mut().push(pass_budget);
+ let next = script
+ .borrow_mut()
+ .pop_front()
+ .expect("the loop asked for more passes than the script holds");
+ async move { next }
+ })
+ .await;
+ (out, asked.into_inner())
+}
+
+#[tokio::test]
+async fn stops_when_the_connector_reports_the_end() {
+ // 320 records: one full pass, then a short one that says "done".
+ let (out, asked) = drive(
+ SINGLE_CALL_ITEM_BUDGET,
+ vec![Ok(pass(200, true)), Ok(pass(120, false))],
+ )
+ .await;
+ let out = out.expect("both passes succeed");
+ assert_eq!(asked, vec![SYNC_PASS_MAX_ITEMS, SYNC_PASS_MAX_ITEMS]);
+ assert_eq!(out.written, 320);
+ assert_eq!(out.records_read, 320);
+ assert!(!out.more_pending, "the last pass's word wins");
+}
+
+#[tokio::test]
+async fn stops_when_the_budget_is_spent_and_says_more_is_pending() {
+ // An account bigger than the budget: 200 + 200 + the 100 remainder, then
+ // stop even though the connector still has more — that is the ceiling the
+ // single-call entry points always had, now in deadline-sized calls.
+ let (out, asked) = drive(
+ SINGLE_CALL_ITEM_BUDGET,
+ vec![
+ Ok(pass(200, true)),
+ Ok(pass(200, true)),
+ Ok(pass(100, true)),
+ ],
+ )
+ .await;
+ let out = out.expect("all passes succeed");
+ assert_eq!(asked, vec![SYNC_PASS_MAX_ITEMS, SYNC_PASS_MAX_ITEMS, 100]);
+ assert_eq!(out.written, u32::try_from(SINGLE_CALL_ITEM_BUDGET).unwrap());
+ assert!(
+ out.more_pending,
+ "the caller must learn the account is not drained"
+ );
+}
+
+#[tokio::test]
+async fn a_small_account_is_still_one_pass() {
+ let (out, asked) = drive(SINGLE_CALL_ITEM_BUDGET, vec![Ok(pass(37, false))]).await;
+ let out = out.expect("one pass succeeds");
+ assert_eq!(asked, vec![SYNC_PASS_MAX_ITEMS]);
+ assert_eq!(out.written, 37);
+ assert!(!out.more_pending);
+}
+
+#[tokio::test]
+async fn a_pass_error_ends_the_run_with_that_error() {
+ let (out, asked) = drive(
+ SINGLE_CALL_ITEM_BUDGET,
+ vec![Ok(pass(200, true)), Err("module went away".to_string())],
+ )
+ .await;
+ assert_eq!(out.unwrap_err(), "module went away");
+ assert_eq!(asked.len(), 2, "no pass is attempted after the failure");
+}
+
+#[tokio::test]
+async fn already_ingested_holds_only_when_every_pass_was_a_no_op() {
+ let noop = SyncPassOutcome {
+ records_read: 200,
+ written: 0,
+ already_ingested: true,
+ more_pending: true,
+ message: None,
+ };
+ let last = SyncPassOutcome {
+ more_pending: false,
+ ..noop.clone()
+ };
+ let (out, _) = drive(SINGLE_CALL_ITEM_BUDGET, vec![Ok(noop.clone()), Ok(last)]).await;
+ let out = out.expect("passes succeed");
+ assert!(out.already_ingested, "two no-op passes are a no-op run");
+ assert_eq!(out.records_read, 400);
+ assert_eq!(out.written, 0);
+
+ let (out, _) = drive(SINGLE_CALL_ITEM_BUDGET, vec![Ok(noop), Ok(pass(5, false))]).await;
+ assert!(
+ !out.expect("passes succeed").already_ingested,
+ "one write makes it a run that wrote"
+ );
+}
+
+#[tokio::test]
+async fn the_last_pass_note_wins_present_or_absent() {
+ let noted = SyncPassOutcome {
+ message: Some(" daily request budget spent ".to_string()),
+ ..pass(200, true)
+ };
+ let noted = SyncPassOutcome {
+ more_pending: false,
+ ..noted
+ };
+ let (out, _) = drive(
+ SINGLE_CALL_ITEM_BUDGET,
+ vec![Ok(pass(200, true)), Ok(noted)],
+ )
+ .await;
+ assert_eq!(
+ out.expect("passes succeed").message.as_deref(),
+ Some(" daily request budget spent "),
+ "the note rides through untouched; the stage detail trims it"
+ );
+
+ let noted = SyncPassOutcome {
+ message: Some("stopped short".to_string()),
+ ..pass(200, true)
+ };
+ let (out, _) = drive(
+ SINGLE_CALL_ITEM_BUDGET,
+ vec![Ok(noted), Ok(pass(10, false))],
+ )
+ .await;
+ assert_eq!(
+ out.expect("passes succeed").message,
+ None,
+ "a pass that completes cleanly must not inherit an earlier pass's note"
+ );
+}
+
+#[tokio::test]
+async fn the_budget_counts_records_read_not_records_written() {
+ // Everything the module returns is already ingested, and it keeps saying
+ // more is pending. The old single call fetched 500 and stopped; so does
+ // this — charging the budget by writes would ask forever.
+ let noop = SyncPassOutcome {
+ records_read: 200,
+ written: 0,
+ already_ingested: true,
+ more_pending: true,
+ message: None,
+ };
+ let (out, asked) = drive(
+ SINGLE_CALL_ITEM_BUDGET,
+ vec![
+ Ok(noop.clone()),
+ Ok(noop.clone()),
+ Ok(SyncPassOutcome {
+ records_read: 100,
+ ..noop
+ }),
+ ],
+ )
+ .await;
+ let out = out.expect("passes succeed");
+ assert_eq!(asked, vec![SYNC_PASS_MAX_ITEMS, SYNC_PASS_MAX_ITEMS, 100]);
+ assert_eq!(out.records_read, 500);
+ assert_eq!(out.written, 0);
+ assert!(out.more_pending);
+}
+
+#[tokio::test]
+async fn a_pass_that_reads_nothing_ends_the_run() {
+ // "More pending" with an empty page cannot be acted on: asking again
+ // would fetch the same nothing. One pass, then stop.
+ let empty = SyncPassOutcome {
+ records_read: 0,
+ written: 0,
+ already_ingested: false,
+ more_pending: true,
+ message: None,
+ };
+ let (out, asked) = drive(SINGLE_CALL_ITEM_BUDGET, vec![Ok(empty)]).await;
+ let out = out.expect("the pass succeeds");
+ assert_eq!(asked.len(), 1);
+ assert_eq!(out.records_read, 0);
+ assert!(out.more_pending, "the module's own word is still reported");
+}
diff --git a/src/openhuman/integrations/composio/ops/providers_ops.rs b/src/openhuman/integrations/composio/ops/providers_ops.rs
index 45f864fdb9..fd0a996956 100644
--- a/src/openhuman/integrations/composio/ops/providers_ops.rs
+++ b/src/openhuman/integrations/composio/ops/providers_ops.rs
@@ -455,8 +455,8 @@ pub async fn composio_sync_budgeted(
/// What one [`run_sync_pass`] call did.
///
-/// A superset of the `usize` the caller inside this file needs, so
-/// `memory::sync::composio::providers::slack::rpc` — the other caller — can
+/// A superset of the `usize` the caller inside this file needs, so the
+/// single-call entry points behind `pass_budget::run_sync_within_budget` can
/// build a [`SyncOutcome`] without a second round trip through the module.
#[derive(Debug, Clone, Default)]
pub(crate) struct SyncPassOutcome {
@@ -485,11 +485,11 @@ pub(crate) struct SyncPassOutcome {
/// stands, and re-deciding that here would give the run two opinions about
/// what has been read.
///
-/// `pub(crate)` — also called from
-/// `memory::sync::composio::providers::slack::rpc`, which needs the same
-/// tinyconnectors-mediated sync pass `composio_sync` runs here, but awaited
-/// synchronously rather than fired into a background task (its RPC contract
-/// is "return the outcome", not "return that a run started").
+/// `pub(crate)` — also driven by `pass_budget::run_sync_within_budget` for
+/// the entry points that sync once per invocation (periodic tick, manual
+/// provider sync, `connection_created`, the Slack ingest RPC), which repeat
+/// this pass within one call's item budget and await it synchronously rather
+/// than firing it into a background task.
pub(crate) async fn run_sync_pass(
config: &Config,
toolkit: &str,
diff --git a/src/openhuman/integrations/composio/periodic.rs b/src/openhuman/integrations/composio/periodic.rs
index e4080ddecb..fb3cbd52af 100644
--- a/src/openhuman/integrations/composio/periodic.rs
+++ b/src/openhuman/integrations/composio/periodic.rs
@@ -116,12 +116,8 @@ async fn run_one_tick() -> Result<(), String> {
continue;
}
- match crate::openhuman::integrations::composio::ops::run_sync_pass(
- &config,
- &toolkit,
- &conn.id,
- "periodic",
- crate::openhuman::integrations::composio::ops::SYNC_PASS_MAX_ITEMS,
+ match crate::openhuman::integrations::composio::ops::run_sync_within_budget(
+ &config, &toolkit, &conn.id, "periodic",
)
.await
{
diff --git a/src/openhuman/memory/ops/sync.rs b/src/openhuman/memory/ops/sync.rs
index 3b2251f851..149275554e 100644
--- a/src/openhuman/memory/ops/sync.rs
+++ b/src/openhuman/memory/ops/sync.rs
@@ -222,12 +222,11 @@ async fn spawn_manual_sync(requested_connection: Option<String>) -> Result<(), S
// Through the tinyconnectors module and the bound driver's
// `MemorySourceSink`, not the (now permanently refusing) engine
// seam — see `memory::sync::composio`'s module docs.
- let outcome = crate::openhuman::integrations::composio::ops::run_sync_pass(
+ let outcome = crate::openhuman::integrations::composio::ops::run_sync_within_budget(
&config,
&target.toolkit,
&target.connection_id,
"manual",
- crate::openhuman::integrations::composio::ops::SYNC_PASS_MAX_ITEMS,
)
.await;
match outcome {
diff --git a/src/openhuman/memory/sync/composio/bus_part_02.rs b/src/openhuman/memory/sync/composio/bus_part_02.rs
index ad036fca78..3926d91a16 100644
--- a/src/openhuman/memory/sync/composio/bus_part_02.rs
+++ b/src/openhuman/memory/sync/composio/bus_part_02.rs
@@ -333,13 +333,12 @@ impl EventHandler<DomainEvent> for ComposioConnectionCreatedSubscriber {
// bound driver's `MemorySourceSink` instead — the same
// `run_sync_pass` helper every other sync entry point in this
// domain uses now.
- let attempted = crate::openhuman::integrations::composio::ops::run_sync_pass(
+ let attempted = crate::openhuman::integrations::composio::ops::run_sync_within_budget(
&host_config,
&toolkit,
&connection_id,
"connection_created",
- crate::openhuman::integrations::composio::ops::SYNC_PASS_MAX_ITEMS,
-)
+ )
.await;
match attempted {
Ok(pass) => {
diff --git a/src/openhuman/memory/sync/composio/providers/slack/rpc.rs b/src/openhuman/memory/sync/composio/providers/slack/rpc.rs
index 3ceb7e7d88..162852a4d6 100644
--- a/src/openhuman/memory/sync/composio/providers/slack/rpc.rs
+++ b/src/openhuman/memory/sync/composio/providers/slack/rpc.rs
@@ -19,9 +19,11 @@
//! not hold. `sync_trigger_rpc` below reads through the connector module and
//! writes into the bound memory driver via `MemorySourceSink::accept_source_items`
//! instead — the same `run_sync_pass` helper
-//! `integrations::composio::ops::composio_sync` uses, called synchronously
-//! here rather than fired into a background task, because this RPC's
-//! contract is "return the outcome", not "return that a run started".
+//! `integrations::composio::ops::composio_sync` uses (through
+//! `run_sync_within_budget`, which repeats it within one call's item budget),
+//! called synchronously here rather than fired into a background task,
+//! because this RPC's contract is "return the outcome", not "return that a
+//! run started".
//!
//! `sync_status_rpc` genuinely lost capability it cannot honestly recover:
//! the module keeps its sync cursor and daily-request budget internally and
@@ -37,7 +39,7 @@ use crate::openhuman::config::Config;
use crate::openhuman::integrations::composio::client::{
create_composio_client, direct_list_connections, ComposioClientKind,
};
-use crate::openhuman::integrations::composio::ops::run_sync_pass;
+use crate::openhuman::integrations::composio::ops::run_sync_within_budget;
use crate::openhuman::integrations::composio::providers::SyncOutcome;
use crate::openhuman::integrations::composio::types::ComposioConnectionsResponse;
use crate::rpc::RpcOutcome;
@@ -118,15 +120,9 @@ pub async fn sync_trigger_rpc(
// Reads through the `tinyconnectors` module and ingests through the
// bound driver's `MemorySourceSink` — see the module doc comment for
// why this no longer goes through `MemorySourceSync::run_connection_sync`.
- match run_sync_pass(
- config,
- "slack",
- &conn.id,
- "manual",
- crate::openhuman::integrations::composio::ops::SYNC_PASS_MAX_ITEMS,
- )
- .await
- .map_err(|error| error.to_string())
+ match run_sync_within_budget(config, "slack", &conn.id, "manual")
+ .await
+ .map_err(|error| error.to_string())
{
Ok(pass) => outcomes.push(SyncOutcome {
toolkit: "slack".to_string(),