openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

perf(subconscious): bound-concurrent calendar connection fan-out

Open mysma-9403 opened this issue 5 months ago • 5 comments

Summary

  • The heartbeat planner's collect_calendar_meetings now resolves each selected calendar connection's GOOGLECALENDAR_EVENTS_LIST call with a bounded-concurrent buffered fan-out (K=4) instead of one strictly-serial await per connection.
  • Order- and error-preserving: buffered yields in input order, so the flattened PendingEvent stream matches the old serial loop exactly, and a failing connection still contributes zero events (the serial continue).
  • Single-connection ticks (the common case) cost nothing extra; the win shows up for multi-account users (or anyone who raises max_calendar_connections_per_tick).

Problem

Each selected calendar connection is an independent Composio → Google Calendar HTTP round-trip. The old planner awaited them one at a time inside the tick:

for conn in select_calendar_connections_for_tick(connections, cap, now, interval) {
    let resp = match &kind { Backend(c) => c.execute_tool(...).await?, Direct(d) => direct_execute(...).await? };
    out.extend(extract_calendar_events(&resp.data, ...));
}

So a heartbeat tick polling N calendar connections blocked for the sum of all N fetches before the planner could surface upcoming meetings.

Solution

Introduce a narrow, testable seam — a CalendarExecutor trait — over the mode-aware Composio client, then drive the per-connection fetches through a bounded buffered:

  • ComposioCalendarExecutor is the real impl (the Backend/Direct match, unchanged behaviour).
  • fetch_calendar_events_for_connection does the arg-building + apply_calendar_query_defaults + extraction (or empty-on-error), and is unit-tested with a fake executor.
  • collect_calendar_events_buffered materializes the per-connection futures into a Vec and runs them through futures::stream::iter(..).buffered(CALENDAR_FANOUT_CONCURRENCY), then flattens in order.

Key parity points:

  • Order preserved: buffered(K) emits result[i] for input[i], so the flattened events keep their per-connection order.
  • Error semantics preserved: a failed fetch logs and returns an empty Vec — identical to the serial continue.
  • Bounded: CALENDAR_FANOUT_CONCURRENCY = 4 caps sockets; select_calendar_connections_for_tick still caps the selected set to max_calendar_connections_per_tick (default 2) first, so this only matters when a user raises that cap.
  • HRTB: the futures are collected into a Vec before stream::iter — a lazy Map adaptor trips the "implementation of Send is not general enough" error.

One intentional logging tweak: the backend/direct distinction on the failure log moved from two literal message variants ((backend) failed / (direct) failed) to a structured kind field on a single [heartbeat:planner] GOOGLECALENDAR_EVENTS_LIST failed line — same prefix/slug, grep-friendlier, still distinguishes the variant.

Submission Checklist

  • [x] Tests added (happy path + edge cases): calendar_fanout_preserves_connection_order (5 conns > K, asserts input order), calendar_fanout_runs_connections_concurrently (asserts observed max in-flight > 1, i.e. real overlap), calendar_fanout_isolates_failed_connection (middle connection errors → drops out, survivors keep order). Existing select_calendar_connections_for_tick tests unchanged.
  • [x] Diff coverage ≥ 80%: the fan-out driver, per-connection fetch (Ok + Err/warn branches), and kind_label are all exercised by the fake-executor tests; only the ~6-line real Backend/Direct match remains client-bound (untestable without a live Composio client).
  • [x] N/A: Coverage matrix — behaviour-preserving perf change, no feature rows added/removed/renamed.
  • [x] No new external network dependencies (same execute_tool/direct_execute, just concurrent).
  • [x] N/A: no linked issue — proactive performance improvement.

Impact

  • Runtime: Rust core subconscious heartbeat planner (collect_calendar_meetings).
  • Latency: a tick polling N calendar connections now resolves them in ~ceil(N/4) round-trips instead of N. No change for single-connection ticks.
  • No migration, security, or compatibility implications; per-connection arg defaulting, extraction, and the tick-rotation cap are untouched.

Parity Contract

  • Legacy behaviour preserved: each connection goes through the identical arg-building → apply_calendar_query_defaults → execute → extract_calendar_events path; output order and per-connection error isolation are unchanged.
  • Guard/fallback parity: the select_calendar_connections_for_tick rotation + max_calendar_connections_per_tick cap, the is_calendar_connection filter, and the all-day-event exclusion (start.dateTime only) all run exactly as before.

Summary by CodeRabbit

  • Performance Improvements

    • Calendar collection now uses bounded parallel fetching across connections, reducing wait times while limiting concurrent requests.
  • Reliability

    • Individual connection failures or unsuccessful provider responses no longer block others; failed sources contribute no events.
    • Per-connection ordering is preserved when merging results.
  • Tests

    • Added tests validating concurrency limits, failure isolation, and order preservation.

mysma-9403 avatar Jun 07 '26 00:06 mysma-9403

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2ad36fed-339f-4c9e-8276-1e5afea21212

📥 Commits

Reviewing files that changed from the base of the PR and between 7b933600519fae5c8b7835a0e4c6c301afcd020c and 96e27bf2a684eeb9db2a944e692ab578417139bb.

📒 Files selected for processing (1)
  • src/openhuman/subconscious/heartbeat/planner/collectors.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openhuman/subconscious/heartbeat/planner/collectors.rs

📝 Walkthrough

Walkthrough

Refactors calendar meeting collection to a bounded-concurrency, ordered fan-out using a CalendarExecutor abstraction and futures::stream::buffered; failures yield no events and collect_calendar_meetings delegates to a helper that selects tick connections and fans out fetches.

Changes

Calendar Event Fan-Out Pipeline

Layer / File(s) Summary
Import for buffered streams
src/openhuman/subconscious/heartbeat/planner/collectors.rs
Added futures::stream::StreamExt to support the buffered fan-out implementation.
Calendar executor trait and buffered fan-out infrastructure
src/openhuman/subconscious/heartbeat/planner/collectors.rs
Added CALENDAR_FANOUT_CONCURRENCY, CalendarExecutor and ComposioCalendarExecutor.
Per-connection fetch and buffered collector
src/openhuman/subconscious/heartbeat/planner/collectors.rs
Added fetch_calendar_events_for_connection() (applies timezone/query defaults, extracts PendingEvents, returns [] on error) and collect_calendar_events_buffered() which runs per-connection fetch futures via futures::stream::iter().buffered() while preserving input order and flattening results.
Integration: collect_calendar_meetings -> fan-out helper
src/openhuman/subconscious/heartbeat/planner/collectors.rs
collect_calendar_meetings() now constructs ComposioCalendarExecutor and delegates to collect_calendar_meetings_with(), which computes the end window, selects tick-appropriate connections, logs start/complete, and invokes the buffered collector instead of a serial loop.
FakeExecutor tests for buffered behavior
src/openhuman/subconscious/heartbeat/planner/collectors.rs
Added Tokio tests with an in-memory FakeExecutor (controllable delays and concurrency tracking) validating order preservation under buffering, concurrent overlap via max in-flight observations, failure isolation (failed connection yields no events), and correct connection selection + in-order fan-out.

Sequence Diagram

sequenceDiagram
  participant Planner
  participant Collector as collect_calendar_events_buffered
  participant StreamBuf as StreamBuffer(CALENDAR_FANOUT_CONCURRENCY)
  participant FetchHelper as fetch_calendar_events_for_connection
  participant Executor as CalendarExecutor

  Planner->>Collector: collect_calendar_events_buffered(connections, executor)
  Collector->>StreamBuf: iter(connections).buffered(max_concurrent)
  loop For each connection (concurrent, bounded)
    StreamBuf->>FetchHelper: invoke fetch for connection
    FetchHelper->>Executor: GOOGLECALENDAR_EVENTS_LIST query
    Executor-->>FetchHelper: events or error
    FetchHelper-->>StreamBuf: Vec<PendingEvent> (or [])
  end
  StreamBuf->>Collector: flattened results in original connection order
  Collector-->>Planner: Vec<PendingEvent>

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 I buffered through the morning light,

Fan-out hops in tidy, ordered flight,
Failed sprouts fall quiet, left aside,
Concurrent carrots spread wide,
The planner hums — my tidy stride.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'perf(subconscious): bound-concurrent calendar connection fan-out' accurately summarizes the main change: introducing bounded-concurrent fan-out for calendar connection fetching, replacing serial polling.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jun 07 '26 00:06 coderabbitai[bot]

@coderabbitai review

The requested fan-out lifecycle debug logs were added in a1eb25f0: collect_calendar_meetings_with now logs a [heartbeat:planner] calendar fan-out start line (executor, selected count, connection limit, lookahead/interval window, concurrency cap, now/end_window) before the buffered fetch and a calendar fan-out complete line (selected + final event count) after it. Please re-review.

mysma-9403 avatar Jun 12 '26 21:06 mysma-9403

[!TIP] For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Fetch the PR diff
gh pr view 3472 --repo tinyhumansai/openhuman --json title,state,headRefName,baseRefName,commits,files

# Get the latest diff
gh pr diff 3472 --repo tinyhumansai/openhuman 2>/dev/null | head -800

Length of output: 22277


🏁 Script executed:

#!/bin/bash
# Read the main file under review
fd -e rs collectors --type f | xargs cat 2>/dev/null | head -600

Length of output: 21137


🏁 Script executed:

#!/bin/bash
# Alternatively, try to find the collectors.rs file
find . -type f -name "collectors.rs" | head -5
cat src/openhuman/subconscious/heartbeat/planner/collectors.rs 2>/dev/null || \
  find . -path "*/heartbeat/planner/collectors.rs" -exec cat {} \;

Length of output: 32372



@mysma-9403 The lifecycle logs look correct and well-placed. Here's a full pass:

Commit a1eb25f0 — lifecycle log review

Check Result
"fan-out start" placement ✅ Fires after select_calendar_connections_for_tick, so selected.len() is already resolved
"fan-out start" fields ✅ Covers all correlation state: executor, selected, calendar_connection_limit, meeting_lookahead_minutes, interval_minutes, concurrency, now, end_window
"fan-out complete" placement ✅ Fires after the await, so events.len() is the actual result count
target: convention ✅ No explicit target on lifecycle logs — consistent with other [heartbeat:planner] lines in the file; target: "composio" is reserved for per-API-call sites

Two minor observations (non-blocking):

  1. "fan-out complete" omits executor/now — at high tick frequency, if two ticks overlap in logs, you lose the executor kind on the "complete" line. If you want full correlation without a log-join, adding executor = executor.kind_label() to the complete log would close the gap. Cosmetic for now.

  2. Double-log on the empty-selected path — select_calendar_connections_for_tick already emits a debug!(eligible=0 …) log, so the fan-out "start" + "complete" both fire immediately after with selected=0/events=0. Three debug lines for the no-op case. Harmless, but worth knowing if you're reading noisy logs.

Existing implementation — no new concerns:

  • collect_calendar_events_buffered correctly materialises futures into a Vec before stream::iter (HRTB fix is sound and documented)
  • buffered(K) order preservation is correctly tested with 5 connections wrapping the K=4 window
  • FakeExecutor AtomicUsize inflight probe with SeqCst is correct; tokio::time::sleep yields in the single-threaded test runtime so max_inflight > 1 holds
  • Error isolation test (middle connection "boom") correctly verifies ["evt-1", "evt-3"] output order

The PR is ready. Approving.

[approve]

coderabbitai[bot] avatar Jun 12 '26 21:06 coderabbitai[bot]

Thanks for the thorough re-review @coderabbitai. Addressed observation 1 in 7b933600: the calendar fan-out complete log now carries executor = executor.kind_label(), so the start/complete pair correlates by executor kind without a log-join.

Leaving observation 2 (triple debug line on the empty-selected path) as-is on purpose: the start/complete bracket is a deliberate lifecycle trace, and select_calendar_connections_for_tick only emits its eligible=0 line when the cap actually selects nothing — three debug-level lines for a genuine no-op tick is acceptable noise and guarding it would add a branch for zero functional gain. Happy to revisit if it shows up as real log pressure.

mysma-9403 avatar Jun 13 '26 07:06 mysma-9403

[!TIP] For best results, initiate chat on the files or code changes.

@mysma-9403 Looks good — the executor = executor.kind_label() addition in 7b933600 closes the correlation gap cleanly.

The reasoning on observation 2 is sound: the start/complete bracket is a meaningful lifecycle invariant, and shielding it behind an early-return guard would be optimising for log aesthetics at the cost of a non-trivial branch. Debug-level noise on a genuine no-op tick is well within acceptable bounds. Happy to leave it as-is.

🐇 ✨


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

coderabbitai[bot] avatar Jun 13 '26 07:06 coderabbitai[bot]