Skip to content

feat(subagent): give spawned sub-agents a condenser by default - #3696

Merged
ak684 merged 1 commit into
mainfrom
alona/sdk-subagent-condenser
Jun 14, 2026
Merged

ak684 merged 1 commit into
mainfrom
alona/sdk-subagent-condenser

Conversation

@ak684

@ak684 ak684 commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

Closes the gap where spawned sub-agents had no condenser and dead-ended on context overflow. Reviewed the change and the real-LLM before/after. Subagents now auto-compact and keep going instead of eventually error'ing out on large workflows.

  • A human has tested these changes.

AGENT:


Why

Spawned sub-agents (the task / delegate / workflow tools) never received the summarizing condenser that every top-level agent gets, so a deep sub-agent run dead-ended on context-window overflow instead of auto-compacting. This made sub-agents a special case that silently lacked the context management the main
agent has.

Summary

  • agent_definition_to_factory now attaches a default summarizing condenser to sub-agents, sharing sizing with the standard preset via a new default_condenser SDK helper (get_default_condenser delegates to it).
  • The condenser LLM uses a distinct usage_id="condenser" so its tokens are tracked, not deduped out of conversation stats (first-write-wins on usage_id).
  • New optional AgentDefinition.condenser field keeps it overridable and serializes for the remote agent-server path: omit/None → default; none/false → NoOpCondenser (disable); a mapping → a custom condenser spec.

How to Test

Unit + full suite (in this branch's worktree):

uv run pytest tests/sdk tests/tools         # 5500 passed, 11 skipped, 13 xfailed, 0 failed
uv run ruff check && uv run ruff format      # clean
uv run pytest -k condenser tests/sdk/subagent  # 9 new tests

Real-LLM end-to-end before/after (identical 7-message input, run against a live model via the standalone SDK):

events retained condensations fired usage_ids tracked
BEFORE (no condenser) 15 0 ['agent']
AFTER (this change) 16 1 ['agent', 'condenser']

Live AFTER log excerpt:

[A] default factory condenser OK: max_size=80 usage_id=condenser
Auto Conversation Condensation Triggered. Forgetting 9 events
  [Summary of Events Being Forgotten] ... (real LLM-generated summary)
[B] events=16 condensation_events=1 usage_ids=['agent', 'condenser']

BEFORE never compacts — the view grows unbounded (the path that eventually overflows
the real context window). AFTER fires the condenser (summarized + forgot 9 events),
the sub-agent continues, and its tokens are tracked under a distinct condenser
usage_id.

Note on the BEFORE row: it is the faithful illustration of the mechanism, not a
literal crash. Triggering an actual context-window-exceeded error live would
require filling a ~200k-token window (expensive/slow), so the contrast above is
the cheap, faithful demonstration of why the dead-end happens. The AFTER fix
was verified firing end to end against a real LLM.

Type

  • Feature

Notes

Additive and back-compat: the new field defaults to today's behavior, programmatic agents built without the factory are unaffected, and AgentDefinition.condenser is serialization-safe for the remote path (CondenserBase is a discriminated union; round-trip covered by a test).

Spawned sub-agents (task/delegate/workflow) were a special case that never got
the summarizing condenser every top-level agent has, so a deep sub-agent run
dead-ended on context-window overflow instead of auto-compacting.

agent_definition_to_factory now attaches a default summarizing condenser to
sub-agents (shared sizing with the preset via a new sdk default_condenser
helper), using a distinct usage_id so its tokens are tracked rather than
deduped out of conversation stats. Add an optional AgentDefinition.condenser
field (markdown: omit for default, 'none'/false to disable, mapping for a
custom spec) so it stays overridable and serializes for the remote path.
@github-actions

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ QA Report: PASS WITH ISSUES

The sub-agent condenser behavior works as described in real SDK usage; the only issue I found is the existing PR Description Check failure, which needs a human PR-description update.

Does this PR achieve its stated goal?

Yes. On main, a Markdown-loaded sub-agent factory produced an agent with agent_condenser: null, so spawned sub-agents had no default compaction path. On this PR, the same SDK flow produces LLMSummarizingCondenser with max_size: 80, keep_first: 4, and a separate condenser usage ID; condenser: none and condenser: false both produce NoOpCondenser. I also exercised the PR branch with a live LLM-backed condenser call over 90 events, and it returned a real Condensation with a summary and 51 forgotten events.

Phase Result
Environment Setup ✅ make build completed successfully and installed the uv environment.
CI Status ⚠️ Functional checks mostly green/in progress; Validate PR description is failing with template/HUMAN-field errors.
Functional Verification ✅ Default condenser, opt-out frontmatter, sizing parity, distinct usage ID, and live condensation were verified through SDK calls.
Functional Verification

Test 1: File-based sub-agent factory default and opt-out behavior

Step 1 — Reproduce / establish baseline without the fix:
Ran git checkout --detach origin/main && uv run python /tmp/qa_subagent_condenser.py.

Relevant output:

{"agent_condenser": null, "agent_llm_usage_id": "agent", "definition_condenser": null, "label": "absent", "metadata_keys": []}
{"agent_condenser": null, "definition_condenser": null, "label": "disabled_string", "metadata_keys": ["condenser"]}
{"agent_condenser": null, "definition_condenser": null, "label": "disabled_boolean", "metadata_keys": ["condenser"]}
{"label": "top_level_default_preset", "preset_condenser": "LLMSummarizingCondenser", "preset_keep_first": 4, "preset_llm_usage_id": "agent", "preset_max_size": 80}

This confirms the old behavior: the top-level preset had a summarizing condenser, but file-based spawned sub-agents got no condenser by default, and condenser frontmatter was just metadata.

Step 2 — Apply the PR's changes:
Checked out origin/alona/sdk-subagent-condenser at f13075b1adf87a4b4c0519e22092ce21cfdab54d.

Step 3 — Re-run with the fix in place:
Ran uv run python /tmp/qa_subagent_condenser.py.

Relevant output:

{"agent_condenser": "LLMSummarizingCondenser", "agent_llm_usage_id": "agent", "condenser_keep_first": 4, "condenser_llm_usage_id": "condenser", "condenser_max_size": 80, "definition_condenser": null, "label": "absent", "metadata_keys": []}
{"agent_condenser": "NoOpCondenser", "definition_condenser": "NoOpCondenser", "label": "disabled_string", "metadata_keys": []}
{"agent_condenser": "NoOpCondenser", "definition_condenser": "NoOpCondenser", "label": "disabled_boolean", "metadata_keys": []}
{"label": "top_level_default_preset", "preset_condenser": "LLMSummarizingCondenser", "preset_keep_first": 4, "preset_llm_usage_id": "agent", "preset_max_size": 80}

This shows the PR delivers the promised default condenser, keeps sizing aligned with the top-level preset, tracks condenser calls under a distinct usage ID, and makes the documented opt-out frontmatter work without leaking into metadata.

Test 2: Live condenser execution on the spawned sub-agent default

Step 1 — Reproduce / establish baseline without the fix:
The baseline run above showed agent_condenser: null for an omitted condenser field, so there was no spawned-sub-agent condenser to invoke by default.

Step 2 — Apply the PR's changes:
Used the PR branch and the environment-provided LLM configuration (LLM_MODEL, LLM_BASE_URL, LLM_API_KEY) to exercise the actual condenser object created by agent_definition_to_factory.

Step 3 — Re-run with the fix in place:
Ran OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_condense_real.py.

Output:

{"condenser_type": "LLMSummarizingCondenser", "condenser_usage_id": "condenser", "forgotten_event_count": 51, "input_events": 90, "llm_response_id_present": true, "result_type": "Condensation", "summary_offset": 4, "summary_present": true}

This confirms the spawned sub-agent's default condenser does not just exist structurally; it successfully performed a real LLM-backed condensation, produced a summary, and forgot old events.

CI note

I did not run the test suite, linters, formatters, or type checkers. I only checked CI status via GitHub.

The failed Validate PR description job reported:

The first visible line of the PR description must be `HUMAN:`.
Add a short human-written note between `HUMAN:` and the human-tested checkbox.
Keep the `- [ ] A human has tested these changes.` checkbox in the PR description.
Keep the `AGENT:` marker from the PR template.
Keep the `## Why` section from the PR template.
Keep the `## Summary` section from the PR template.
Keep the `## How to Test` section from the PR template.
PR description validation failed with 7 error(s).

Per repository guidance, those human-only PR description fields should be updated by a human, not by an AI agent.

Issues Found

  • 🟡 Non-functional CI issue: Validate PR description is failing because the PR description does not match the required template/HUMAN-field format. No functional defect was found in the PR behavior I exercised.

Final verdict: PASS WITH ISSUES.

This QA review was created by an AI agent (OpenHands) on behalf of the user.

@github-actions

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/context/condenser
   llm_summarizing_condenser.py1723579%305, 308–309, 312–313, 318, 323, 325–326, 339–340, 394–398, 400, 415–416, 421, 429, 445–446, 448–450, 455–459, 462, 466, 468–469
openhands-sdk/openhands/sdk/subagent
   registry.py132695%117, 243–244, 248, 305–306
   schema.py1391192%61, 74, 93, 108, 138, 168, 175–177, 266, 269
openhands-tools/openhands/tools/preset
   default.py53492%62, 64, 111–112
TOTAL31324881371% 

@ak684
ak684 requested a review from all-hands-bot June 14, 2026 17:55

all-hands-bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

🟢 Good taste — elegant, well-scoped solution

Summary

This PR solves a real problem: sub-agents spawned by the top-level agent had no condenser by default, causing context overflow errors during deep multi-turn runs. The fix extracts a shared default_condenser() function that both the top-level preset and sub-agent factory use, ensuring consistent behavior and sizing across all agent levels.

Design Quality

The solution is clean and pragmatic:

  1. Shared constant (_DEFAULT_MAX_SIZE, _DEFAULT_KEEP_FIRST) in llm_summarizing_condenser.py keeps sizing in sync — any future change to these values automatically propagates to both the top-level agent and spawned sub-agents.

  2. Distinct usage_id="condenser" is the right call. The LLM tracks token usage by usage_id, and without a distinct ID, condenser calls would overwrite agent calls in the stats. The code handles this correctly with llm.model_copy(update={"usage_id": "condenser"}).

  3. Flexible opt-out: The frontmatter parser handles none, false, off, etc., with a sensible default (None → use summarizing condenser). This gives users escape hatches without complicating the happy path.

  4. _extract_condenser function is well-designed — it returns None for absent/default, NoOpCondenser() for explicit disable, and a validated CondenserBase for explicit configs. The type coercion (bool → NoOpCondenser, dict → validated model) is clean.

  5. Tests are substantive: They verify actual behavior (type checks, value assertions) rather than just mocking calls.

No Issues Found

  • No breaking changes to existing APIs
  • No unnecessary complexity introduced
  • No security concerns
  • No tests missing for new behavior

Minor Note

The PR description validation is failing due to template/HUMAN-field format requirements. Per the existing QA review, that's a non-functional issue that needs a human to update the PR description.

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟢 LOW
    This is a low-risk change that adds a beneficial default (context condensation) to sub-agents. Existing behavior is preserved for users who explicitly opt out. The shared constants actually reduce future maintenance risk by preventing drift between top-level and sub-agent settings.

VERDICT:
✅ Worth merging — solid implementation solving a real problem with good design choices.

KEY INSIGHT:
Extracting default_condenser() as a shared factory function is the right abstraction — it centralizes the sizing constants and ensures the top-level agent and spawned sub-agents always stay in sync.


Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:

  1. Add a .agents/skills/custom-codereview-guide.md file to your branch (or edit it if one already exists) with the /codereview trigger and the context the reviewer is missing (e.g., "Security concerns about X do not apply here because Y"). See the customization docs for the required frontmatter format.
  2. Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
  3. When your PR is merged, the guideline file goes through normal code review by repository maintainers.

Resolve with AI? Install the iterate skill in your agent and run /iterate to automatically drive this PR through CI, review, and QA until it's merge-ready.

Was this review helpful? React with 👍 or 👎 to give feedback.


This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ QA Report: PASS

Verified via real SDK execution that spawned file-based sub-agents now get a default summarizing condenser, can disable it via frontmatter, and can run a live condensation.

Does this PR achieve its stated goal?

Yes. On origin/main, the same sub-agent factory path produced agent_condenser=None, confirming spawned sub-agents had no condenser. On PR head f13075b1, default and file-loaded sub-agents produced LLMSummarizingCondenser with usage_id=condenser; condenser: none / false produced NoOpCondenser; and a live LLM-backed condenser call over 85 events returned a Condensation with a summary.

Phase Result
Environment Setup ✅ make build completed and installed the editable SDK/tools/workspace/server packages.
CI Status ⚠️ gh pr checks showed 35 successful, 0 failing, 2 skipped, and 1 pending qa-changes check (this run).
Functional Verification ✅ Before/after SDK probes and a live condenser call matched the PR goal.
Functional Verification

Test 1: Default spawned sub-agent condenser and frontmatter controls

Step 1 — Reproduce / establish baseline without the fix:
Ran git checkout --detach origin/main then uv run python /tmp/qa_subagent_condenser.py:

default_frontmatter.agent_condenser=None
default_frontmatter.condenser_usage_id=None
default_frontmatter.agent_usage_id=default
default_frontmatter.metadata_has_condenser=False
disabled_frontmatter.agent_condenser=None
disabled_frontmatter.condenser_usage_id=None
disabled_frontmatter.agent_usage_id=default
disabled_frontmatter.metadata_has_condenser=True
false_frontmatter.agent_condenser=None
false_frontmatter.condenser_usage_id=None
false_frontmatter.agent_usage_id=default
false_frontmatter.metadata_has_condenser=True

This confirms the old behavior: sub-agent factories created agents with no condenser, and condenser: frontmatter was treated as metadata instead of a behavior control.

Step 2 — Apply the PR's changes:
Checked out alona/sdk-subagent-condenser at f13075b1.

Step 3 — Re-run with the fix in place:
Ran uv run python /tmp/qa_subagent_condenser.py:

default_frontmatter.agent_condenser=LLMSummarizingCondenser
default_frontmatter.condenser_usage_id=condenser
default_frontmatter.agent_usage_id=default
default_frontmatter.metadata_has_condenser=False
disabled_frontmatter.agent_condenser=NoOpCondenser
disabled_frontmatter.condenser_usage_id=None
disabled_frontmatter.agent_usage_id=default
disabled_frontmatter.metadata_has_condenser=False
false_frontmatter.agent_condenser=NoOpCondenser
false_frontmatter.condenser_usage_id=None
false_frontmatter.agent_usage_id=default
false_frontmatter.metadata_has_condenser=False

This shows the default sub-agent now gets a summarizing condenser with a distinct condenser usage id, while explicit disable values produce a no-op condenser.

Test 2: File-based sub-agent loading path and live condensation

Step 1 — Reproduce / establish baseline without the fix:
Ran the same construction path on origin/main using the configured LLM settings, without invoking the LLM because no condenser existed:

agent_condenser=None
condense_probe_skipped=no_subagent_condenser_available

This confirms the runtime sub-agent could not compact because there was no condenser to call.

Step 2 — Apply the PR's changes:
Checked out alona/sdk-subagent-condenser at f13075b1.

Step 3 — Re-run with the fix in place:
First exercised the file-based agent path using load_agents_from_dir(...) → agent_definition_to_factory(...):

loaded_agent_count=1
loaded_agent_name=researcher
spawned_agent_condenser=LLMSummarizingCondenser
spawned_condenser_usage_id=condenser

Then ran a live LLM-backed condenser call through the spawned sub-agent's default condenser:

agent_condenser=LLMSummarizingCondenser
condenser_usage_id=condenser
condense_result_type=Condensation
condense_result_event_count=0
condense_summary_present=True

This demonstrates the PR path does more than instantiate the object: the spawned sub-agent's default condenser can actually call the configured LLM and produce a condensation summary.

Test 3: Default preset parity and serialization

Ran the public default-preset and AgentDefinition serialization APIs on PR head:

top_level_default_condenser=LLMSummarizingCondenser
top_level_default_max_size=80
top_level_default_keep_first=4
frontmatter_none_condenser=NoOpCondenser
serialized_condenser={'kind': 'NoOpCondenser'}

This confirms the existing top-level default condenser sizing remains 80 / 4, while a disabled sub-agent condenser serializes as a concrete no-op condenser spec for downstream paths.

Issues Found

None.

This QA review was created by an AI agent (OpenHands) on behalf of the user.

@ak684
ak684 merged commit 3927aa4 into main Jun 14, 2026
47 of 49 checks passed
@ak684
ak684 deleted the alona/sdk-subagent-condenser branch June 14, 2026 18:05
@VascoSch92

Copy link
Copy Markdown
Member

@ak684 this pr add an api for file-based agent which i'm not sire it is what we wanted.

There it was already another PR for that: https://github.com/OpenHands/software-agent-sdk/pull/2349/files

@VascoSch92

Copy link
Copy Markdown
Member

The default sub-agent condenser (the PR's main goal) is token-correct and unaffected.

Both trace to the passthrough at subagent/registry.py:262, which — unlike the else branch — neither freshens the instance per spawn nor normalizes the condenser LLM's usage_id.

  condenser = (
      agent_def.condenser                       # <- passed by reference, usage_id untouched
      if agent_def.condenser is not None
      else default_condenser(llm.model_copy(update={"usage_id": "condenser"}))
  )

Both were reproduced through the real LocalConversation → llm_registry.add() → ConversationStats path (no LLM calls; tokens recorded the way Telemetry would).

  • a custom condenser instance is shared across every sub-agent spawn → metrics double-count. The default branch builds a fresh condenser each call; the explicit branch hands every spawn the same object (same LLM, same Metrics). Two sub-agent tasks of the same type then accumulate into one shared metrics object:
  task#1 condenser tokens right after task#1 : 500   (correct)
  task#1 condenser tokens after task#2 ran   : 1000  (should still be 500)
  two conversations share ONE metrics object : True

Impact: inflated/cross-contaminated condenser cost, propagated to the parent via the task:{id} rollup; under concurrent same-type sub-agents it's also a mutable-state race on the shared Metrics/Telemetry.

  • the explicit path doesn't enforce a distinct usage_id → silent token loss. If a custom condenser's LLM shares the agent's usage_id (trivially easy — both default to "default", or a frontmatter condenser:
    mapping that omits usage_id), the registration dedup (local_conversation.py:855) drops it.

@VascoSch92

Copy link
Copy Markdown
Member

Moreover, the docs should be update for file-based agents

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants