Skip to content

Five structures behind most of our bug fixes, and an order to refactor them #6456

Open

Description

@VascoSch92

I went through the 602 defect fixes in this repo's history (every fix with a linked bug issue, plus the fix commits without one, each with a one-line root-cause note) and grouped them by the structure in the code that made the bug possible, rather than by symptom. Five structures cover about 86% of them; the rest are local mistakes with no structural cause. The grouping was done from the one-line notes, not by re-reading every diff, so treat the counts as indicative. A spot check of 10–20 bugs per group before committing to a quarter of work is cheap. Code links are pinned to 73459e9.

Structure Distinct bugs Share of 602
The same behaviour is implemented on parallel paths with no shared core 150 25%
The external world is modelled by string matching and scraping 133 22%
One fact is stored in several places and kept in sync by hand 108 18%
Lifecycle, status and ownership are enforced by convention 95 16%
Cross-cutting concerns (errors, secrets, config) are applied per call site 76 13%

1. The same behaviour is implemented on parallel paths (150)

Sync and async are two full implementations: run → _run → Agent.step → LLM.completion, and arun → _arun → astep → acompletion. Neither wraps the other. There are 44 such sync/async twin pairs in the SDK. _run and _arun are only 47% similar after stripping await, so they have already diverged, while _step/_astep are 87% similar, i.e. hand-maintained copies. The async path landed in #3284, and 19 later fixes name arun/astep explicitly: #3355 (retry loop outside the try only in the async paths, skipping fallback and telemetry), #3451 (the async copies dropped @observe), #3486 (switch_llm from a tool thread deadlocks on the lock arun holds). Chat Completions and Responses are a second axis (responses, aresponses), so the LLM transport exists four times (#1895: to_responses_dict dropped images that the chat serializer kept).

LocalConversation and RemoteConversation share 24 method names and almost no code; RemoteState re-implements the state protocol by parsing dicts, and the parity test from #6323 needed five documented exceptions (#2115 hook_config not forwarded, #3398 interrupt() not overridden, #5966 deltas appended to the event cache). ACPAgent is a 4,870-line second agent with its own step, status writes, usage accounting and masking (#3027, #3001, #3628; 25 fixes). An agent can be built by three create_agents (AgentSettingsBase, OpenHandsAgentSettings, ACPAgentSettings), create_agent_from_settings, the profile resolver, _agent_from_base_state, switch_llm/switch_profile and the sub-agent factories, each with its own defaults: #3968 (the profile path built agents with only Finish and Think), #4018 then #4699 (load_project_skills flipped one way, then back), #5417/#5755 (provider connections resolved on load but not on switch_llm or validate). enable_browser is read in 12 files. The Docker runtime host re-implements proxying and mirrors the catalog (11 fixes within weeks of #3403: #5918, #5137, #5132), and four container launchers each decide bind address, ports and key forwarding (#5209, #5164).

2. The external world is modelled by string matching (133)

What a model can do is inferred from substring tables in model_features.py layered over LiteLLM metadata, and provider failures are matched by text in classifier.py. Each new model, proxy alias or LiteLLM release falls through a layer: #2693 (alias missed, so temperature was not stripped and Anthropic returned 400), #5460/#5467 (the bare deepseek entry dropped images for v4), #6189 (LiteLLM rewrote the quota message). 45 fixes, and model_features.py alone has 16 fix commits since May. Terminal completion is detected by regex over PTY screen output, in four backends that each re-implement spawn, env, pager and interrupt (#2742, #1817, then #5485 → #5589 → #6038 on tmux sockets): 24 fixes. Git state is probed by ad hoc subprocess calls in 10 files (git/utils.py); unborn HEAD was fixed three separate times (#3158, #3177, #6229): 17 fixes. Tool schemas exist in five hand-converted forms (tool/schema.py, chat, Responses, MCP, prompt text), and summary/security_risk/kind share the argument namespace with real parameters (#3803, #2633, #2512): 30 fixes.

3. One fact is stored in several places and synced by hand (108)

execution_status lives in ConversationState, in the server's per-conversation record refreshed from base_state.json by stat signatures with "memory wins" rules, in RemoteState, and implicitly in meta.json (#4440: resume read the stale agent copy and reverted LLM switches; #5827: the cold-load path popped credential bindings the live path would have refused). Server config comes from OH_* env, the get_default_config() global in config.py, app.state.config replaced by /api/init, store singletons that keep what they first saw, and helper defaults that read env or ~: #3844 (auth closed over the startup config), #3816 (LLMProfileStore() at 21 call sites ignored OH_PERSISTENCE_DIR), #5921. PersistedSettings keeps three pointers plus a copied agent_settings, with the profile files as a third copy (#4319, #5206); #5535 covers part of this. The LLM object is both serialisable config and live per-conversation state (18 private attrs) and is shared and copied across agent, condenser, title generation and sub-agents: #1997 (one Metrics shared, usage counted twice), #3467 (a reused LLM kept the first conversation's session id), #3248 → #4012 → #4473 (the modify_params lock, then it blocking the loop, then it serialising all LLM I/O). The rules for a valid LLM history are recomputed by the view, the condenser, get_unmatched_actions and crash recovery, and the incremental view and the cold-load path can disagree (#1708, #4932, #2300).

4. Lifecycle, status and ownership are enforced by convention (95)

ConversationExecutionStatus is assigned at about 60 sites in 8 files and there is no transition function (#884, #2720 iteration cap checked before FINISHED so finished runs ended as ERROR, #1511). "May this conversation run?" is decided by each entry point from _run_task, execution_status, the run slot, the pins, the rerun flags and _closing (EventService.run, start_goal_loop, resume_goal_loop repeat the same guard); #3160 → #3364 is a fix chain on exactly this, and #5955 admitted the run after the user message was already saved. A synchronous conversation holding a thread-reentrant lock is hosted inside an asyncio server through roughly 56 hand-placed executor hops (#2296 event reads hung on the lock run() holds, #3349 deadlock between arun and the stats callback, #5780 Rich tracebacks rendered on the loop thread). ToolExecutor.close() is a no-op by default and cleanup is spread over __init__, run, close, __del__ and atexit (#3917 delegate leaked terminals and MCP servers, #3083). PubSub is a dict of callables awaited with gather; each subscriber builds its own buffering and timers, and idle eviction is inferred from the stream (#4689 → #4790, #1192 → #5953 → #6046).

5. Cross-cutting concerns are applied per call site (76)

There are 256 hand-raised HTTPExceptions across the routers and _add_exception_handlers maps only three domain exceptions, so anything a route forgets becomes a 500 with str(exc) in the body (#5906 a route copied without its error mapping, #5898 a route outside store_errors() in a file that already used it, #4991/#5795 a bare assert as 500). The October verify sweep found 138 of these in one month. Secrets go through three unrelated mechanisms, regex redaction of text, str.replace masking over whole models, and per-field serializer/validator pairs driven by an untyped context dict, each applied file by file: #6155 then #6259 (masking rewrote an event UUID, then a timestamp), #3422 (an encrypting serializer without a decrypting validator, so ciphertext reached the ACP environment), #5682 (the redaction placeholder sent back on PUT deleted the secret).

Two enabling conditions: all 22 subpackages of openhands.sdk form one load-time import cycle (14 did in October), and the five largest files (acp_agent 4,870 lines, llm 3,552, local_conversation 3,285, conversation_service 3,099, event_service 2,484) appear in 140 of the 540 fix commits since May.

What I propose

One rule first, because the history insists on it: replace a path, never add one. #3284 and #3403 each added a parallel path beside the old one and are the two PRs with the most bugs traced back to them. Each step below should delete the old path in the same PR series, behind test_conversation_parity.py and the persisted-conversation compat test. Ordered by bugs addressed per unit of risk:

  1. Make launch.resolve → finalize the only way an agent or LLM is created or replaced: inline settings, profile, resume, fork, switch_llm/switch_profile, sub-agents, the title LLM, MCP test. Delete the three create_agents and _agent_from_base_state. Make the cipher a required, store-bound argument (Encrypted LLM profiles are decrypted only on the conversation path — FallbackStrategy (and sub-agents) load them without the cipher #4558 is one instance of what this fixes). Guard it with a CI check that AgentContext( and LLMProfileStore.load( only appear under launch/. Medium size, low risk.
  2. A ConversationState.transition(to, reason) validated against a table and emitting the state-update event; migrate the ~60 assignments and forbid raw assignment with a CI grep. Then one RunController in EventService (idle, admitting, running, draining, closing) that owns the permit, the task and the rerun intent behind a single request_run(). Medium, medium risk.
  3. A small domain exception hierarchy (NotFound, Conflict, Invalid, Busy, Unavailable) raised by stores and services and mapped once in _add_exception_handlers; delete the per-route try/except and generate responses= from the mapping. A SecretField type that carries serializer and validator together, with explicit to_disk(cipher) / to_client(mode) / from_client() where from_client rejects blank and placeholder values with 422, and masking once at egress with an allow-list of free-text fields. Enable ruff's ASYNC rules and put store access behind an async facade. Medium, low risk, each part independent.
  4. Typed adapters at external boundaries: one ModelCapabilities per LLM resolved once (overrides, proxy model_info, LiteLLM, then the tables) and read by option builders, serializers and the error mapper; one JSON-Schema IR for tools with renderers for chat, Responses, MCP and prompt text, and meta-fields in a reserved envelope; a Repo object probed once and taken by every git helper; for the terminal, one spawn policy and a side channel for completion and exit status instead of PS1 scraping. Each part independent; the terminal part is the risky one.
  5. Split LLM into an immutable LLMConfig and a per-conversation LLMSession (metrics, telemetry, auth refresh, headers), with the registry keyed by role. One ServerContext built per (re)initialisation, reached only through a request dependency and swapped atomically by /api/init, removing the get_default_* fallbacks and store-constructor defaults. Large.
  6. One async core: LLM.completion/responses as thin wrappers over the async implementation, then Agent.step over astep, then LocalConversation.run over arun, with a lock design that does not need thread reentrancy across the loop. Large and high risk; after 2 and 5.
  7. Collapse the second implementations: RemoteConversation built from the same signature as LocalConversation, seq-numbered replay as the only sync path, response models shared from openhands.sdk and parsed with model_validate; ACPAgent as one backend of a shared turn pipeline (emit events, mask, record usage, map errors) with one adapter per provider; one launch spec rendered by each container backend; the inner server as the only catalog owner in Docker runtime mode. Large; last.
  8. Move shared types (events, ids, status enum, protocols) into a leaf package and enforce layering with import-linter, then split the five big files along the seams the earlier steps create. This is for testability and smaller context per change; fan-in did not predict bugs in the data, so I don't count it as a bug reducer on its own.

Steps 1 to 3 are weeks each and are where I would start. I can break any of them into their own issue once there is agreement on the order.

Related: #5535, #4558, #5390.

Fix PRs per structure (distinct, deduplicated)

T1 same behaviour implemented on parallel paths (150): #801 #802 #857 #871 #904 #906 #917 #949 #951 #1004 #1090 #1141 #1180 #1187 #1206 #1208 #1234 #1245 #1377 #1403 #1444 #1572 #1590 #1619 #1672 #1737 #1791 #1807 #1816 #1832 #1881 #1895 #2115 #2197 #2243 #2323 #2450 #2460 #2630 #2656 #2677 #2698 #2699 #2798 #2897 #2916 #3001 #3027 #3033 #3065 #3167 #3191 #3224 #3355 #3356 #3359 #3381 #3395 #3396 #3398 #3407 #3419 #3451 #3462 #3486 #3493 #3510 #3554 #3556 #3570 #3589 #3614 #3628 #3655 #3737 #3756 #3764 #3816 #3857 #3968 #3975 #3987 #4006 #4009 #4012 #4018 #4124 #4126 #4180 #4186 #4194 #4223 #4280 #4403 #4435 #4476 #4497 #4517 #4566 #4691 #4699 #4876 #4898 #4927 #4952 #4967 #4968 #5000 #5026 #5069 #5078 #5112 #5128 #5130 #5132 #5137 #5140 #5164 #5197 #5204 #5209 #5327 #5358 #5369 #5417 #5434 #5557 #5744 #5755 #5773 #5811 #5851 #5854 #5856 #5874 #5884 #5904 #5909 #5916 #5918 #5943 #5950 #5958 #5964 #5965 #5966 #6029 #6125 #6153 #6157

T2 lifecycle, status and ownership by convention (94): #884 #942 #964 #967 #1039 #1042 #1095 #1192 #1216 #1326 #1400 #1432 #1444 #1511 #1680 #1705 #1732 #1740 #2221 #2222 #2296 #2316 #2369 #2401 #2599 #2622 #2656 #2698 #2720 #2734 #2738 #2805 #2970 #3083 #3113 #3157 #3160 #3166 #3174 #3182 #3184 #3189 #3199 #3200 #3201 #3245 #3349 #3364 #3404 #3462 #3742 #3810 #3866 #3917 #3929 #4036 #4359 #4367 #4378 #4392 #4415 #4417 #4481 #4535 #4548 #4570 #4602 #4689 #4790 #4838 #5026 #5350 #5358 #5362 #5403 #5485 #5489 #5520 #5547 #5559 #5589 #5689 #5759 #5774 #5780 #5794 #5803 #5920 #5945 #5953 #5954 #5955 #6046 #6140

T3 one fact stored in several places (109): #1034 #1115 #1125 #1148 #1153 #1256 #1266 #1371 #1412 #1450 #1508 #1523 #1548 #1577 #1591 #1614 #1705 #1708 #1710 #1997 #2107 #2172 #2221 #2222 #2300 #2323 #2384 #2613 #2736 #2920 #2923 #2973 #2999 #3051 #3063 #3069 #3248 #3258 #3368 #3392 #3407 #3445 #3467 #3483 #3507 #3614 #3633 #3743 #3764 #3816 #3844 #3855 #3857 #3901 #3925 #3927 #3934 #3946 #3953 #3990 #3993 #4012 #4013 #4033 #4068 #4089 #4092 #4124 #4181 #4193 #4198 #4222 #4319 #4320 #4369 #4426 #4440 #4461 #4473 #4476 #4488 #4517 #4814 #4932 #4968 #5069 #5085 #5206 #5241 #5242 #5282 #5661 #5686 #5696 #5700 #5772 #5779 #5817 #5826 #5827 #5865 #5892 #5921 #5924 #5929 #5958 #5973 #6138 #6197

T4 cross-cutting concerns applied per call site (76): #1256 #1423 #1431 #1672 #1862 #1871 #2154 #2171 #2455 #2556 #2631 #2679 #2815 #2962 #3021 #3024 #3041 #3062 #3066 #3074 #3167 #3278 #3299 #3422 #3463 #3464 #3689 #3774 #3873 #3909 #3953 #4099 #4191 #4217 #4279 #4280 #4342 #4506 #4508 #4618 #4783 #4788 #4801 #4839 #4871 #4947 #4991 #5227 #5258 #5551 #5657 #5659 #5660 #5682 #5758 #5770 #5786 #5795 #5798 #5814 #5819 #5821 #5840 #5866 #5867 #5898 #5906 #5917 #5926 #5927 #5931 #6072 #6148 #6155 #6157 #6259

T5 external world modelled by string matching (133): #887 #1011 #1022 #1134 #1153 #1207 #1346 #1366 #1387 #1448 #1464 #1509 #1517 #1580 #1606 #1624 #1668 #1817 #1910 #1956 #1982 #1992 #2096 #2108 #2130 #2138 #2166 #2167 #2182 #2217 #2224 #2238 #2251 #2257 #2264 #2311 #2333 #2334 #2386 #2395 #2512 #2549 #2552 #2601 #2613 #2633 #2635 #2649 #2685 #2693 #2742 #2745 #2746 #2747 #2748 #2753 #2819 #2829 #2884 #3041 #3158 #3171 #3177 #3222 #3247 #3381 #3388 #3394 #3421 #3427 #3429 #3504 #3554 #3586 #3642 #3661 #3684 #3689 #3695 #3735 #3803 #3873 #3941 #4011 #4065 #4087 #4153 #4155 #4185 #4200 #4322 #4341 #4471 #4767 #4836 #4839 #4871 #5024 #5228 #5291 #5309 #5328 #5332 #5460 #5467 #5485 #5587 #5589 #5685 #5703 #5715 #5753 #5754 #5848 #5857 #5885 #5891 #5901 #5905 #5909 #5944 #5986 #5990 #6009 #6038 #6112 #6140 #6148 #6188 #6189 #6213 #6229 #6260


OpenHands AI triage

The following comments and acceptance criteria were added by the OpenHands AI agent.

Triage

Verified against the repository at HEAD: openhands-sdk/openhands/sdk/launch/resolve.py and finalize.py exist as the proposed single creation path, the three create_agent variants and create_agent_from_settings are at the cited locations in settings/model.py, and related issue #4558 (encrypted-profile cipher gap, priority:high, security-related) is live and sits squarely inside proposed step 1.

Bounded scope: this issue is a roadmap tracker, not an implementation issue. Its deliverables are (a) diff-level validation of the per-structure bug grouping and counts, and (b) an explicit recorded disposition for each of the eight proposed steps — a linked child issue with its own bounded scope and observable criteria, or a recorded deferral/rejection with reason. The author's own ordering rule — replace a path, never add one, deleting the old path in the same PR series behind tests/cross/test_conversation_parity.py and the persisted-settings compatibility gate — is adopted as the constraint every resulting child issue must carry.

Non-goals:

  • No code changes land under this tracker; all implementation proceeds through separately scoped child issues.
  • No new parallel implementation paths are added anywhere in the SDK or agent-server as part of this effort.
  • Existing related issues #5535, #4558, and #5390 keep their own scope; this tracker does not absorb or supersede them.
  • Steps 4–8 proceed only through their own child issues after dispositions exist for steps 1–3 (the author's stated starting set).

Prioritized priority:low: the issue aggregates defects that are already fixed and proposes prevention; it records no new user report, support evidence, production incident, or reproduced product failure. The live corroborated pain (e.g. #4558) is already tracked at its own priority in its own issue.

Acceptance Criteria

  • For each of the five structures (parallel paths, string matching, duplicated facts, convention-enforced lifecycle, per-call-site cross-cutting concerns), 10–20 distinct bugs sampled from that structure's deduplicated fix list in this issue are re-read at the diff level, and the per-group results with per-bug verdicts (confirmed / misattributed / reclassified) are recorded in a comment or a document linked from this issue.
  • The five-structure table at the top of this issue is reconciled with the spot-check outcome: either confirmed counts with a dated validation note, or corrected counts and reassignments that list the discrepancies found.
  • Each of the eight proposed steps has an explicit recorded disposition in this tracker: a linked child issue with its own bounded scope and observable acceptance criteria, or a comment recording that the step is deferred or rejected with the reason.
  • Every child issue created for a code step states the replace-don't-add constraint — the old path is deleted in the same PR series, not left running alongside — and names its guards: tests/cross/test_conversation_parity.py and the persisted-settings compatibility gate (.github/scripts/check_persisted_settings_compat.py with tests/sdk/persisted_settings_baselines/) whenever persisted shapes are affected.
  • The non-goals above hold at close: no code changes under this tracker, no parallel paths added, and related issues #5535/#4558/#5390 untouched in scope.

Activity

  1. added
    tracker
    architecture
    proposal
    on Nov 4, 2026
  2. added
    ready-for-dev
    on Nov 4, 2026
  3. enyst commented on Nov 4, 2026

    @enyst
    Member

    One quick thought here, re: local/remote conversation, sync/async

    LLMs are very good at keeping patterns and keeping two things in sync. E.g. my agents maintain a typescript version of the python sdk, and they don’t complain at porting tests, adapting idioms, cross languages, even. Since they didn’t on these, and it’s very obvious in these cases how to do it, it’s likely that they didn’t see it, they didn’t have any clue that they need to look there, or that it’s always always part of touching those files/paths.

    This means we can look at it as a context issue/docstrings/AGENTS.md/lint issue/automation issue. I’m tempted to say, this seems fine to me 🤔

  4. VascoSch92 commented on Nov 4, 2026

    @VascoSch92
    MemberAuthor

    @enyst

    The problem is that you are asking explicitly to do that. But when you add a feature a lot of time an agent forget about that. Yes, giving clear instructions about this parallel patterns is for sure something good and usefull but if we can minimize the problem at the root I think it is better.

    Moreover, a lot of agents don't read the AGENTS.md and the insrtuction from my experience :-)

  5. enyst commented on Nov 4, 2026

    @enyst
    Member

    OK, that works too!

    I’ll use this issue to list quickly what I also had in mind, for whatever fits; if not these, others:

    1/ Lint/guardrails: “if you touched LocalConversation, you must make sure that RemoteConversation works accordingly, and you must include your choices on this in the PR description / design doc.”

    Deterministic wherever possible. A workflow, or an automation.

    2/ Jev-lint
    I’ve been playing with a Jev version of linting. I didn’t continue babysitting it, so I don’t know if it works yet. But it can, it’s for enforcing rules that are not quite deterministic, semantic broken rules.

    Image Image
  6. VascoSch92 commented on Nov 4, 2026

    @VascoSch92
    MemberAuthor

    @enyst About one... I think I do have a pr somewhere for cross-testing this

  7. enyst commented on Nov 4, 2026

    @enyst
    Member

    Just a thought: If you wish to do any of these, it may be worth it to remind the LLM about good ole design patterns, I’m curious if it comes up with them, with fewer hacks and better code.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    architectureproposalready-for-devtracker

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions