{"record":{"id":"1f5dd3229d928a59","repo":"Aider-AI/aider","slug":"unexpected-error-applying-action-action-type-t","errorCode":null,"errorMessage":"Unexpected error applying action '{action.type}' to {action.path}: {e}","messagePattern":"Unexpected error applying action '(.+?)' to (.+?): (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"aider/coders/patch_coder.py","lineNumber":638,"sourceCode":"\n                    # Ensure parent directory exists for target\n                    target_path_obj.parent.mkdir(parents=True, exist_ok=True)\n                    self.io.write_text(target_full_path, new_content)\n\n                    # Remove original file *after* successful write to new location if moved\n                    if action.move_path and full_path != target_full_path:\n                        path_obj.unlink()\n\n                else:\n                    # Should not happen\n                    raise DiffError(f\"Unknown action type encountered: {action.type}\")\n\n            except (DiffError, FileNotFoundError, IOError, OSError) as e:\n                # Raise a ValueError to signal failure, consistent with other coders.\n                raise ValueError(f\"Error applying action '{action.type}' to {action.path}: {e}\")\n            except Exception as e:\n                # Catch unexpected errors during application\n                raise ValueError(\n                    f\"Unexpected error applying action '{action.type}' to {action.path}: {e}\"\n                )\n\n    def _apply_update(self, text: str, action: PatchAction, path: str) -> str:\n        \"\"\"\n        Applies UPDATE chunks to the given text content.\n        Adapted from _get_updated_file in apply_patch.py.\n        \"\"\"\n        if action.type is not ActionType.UPDATE:\n            # Should not be called otherwise, but check for safety\n            raise DiffError(\"_apply_update called with non-update action\")\n\n        orig_lines = text.splitlines()  # Use splitlines to handle endings consistently\n        dest_lines: List[str] = []\n        current_orig_line_idx = 0  # Tracks index in orig_lines processed so far\n\n        # Sort chunks by their original index to apply them sequentially\n        sorted_chunks = sorted(action.chunks, key=lambda c: c.orig_index)","sourceCodeStart":620,"sourceCodeEnd":656,"githubUrl":"https://github.com/Aider-AI/aider/blob/5dc9490bb35f9729ef2c95d00a19ccd30c26339c/aider/coders/patch_coder.py#L620-L656","documentation":"Second, broader wrapper in apply_edits: an exception that is not DiffError/OS-level (e.g. TypeError, IndexError, AttributeError) escaped while applying an action. It signals a bug or unexpected data shape in the apply path, not a normal patch mismatch.","triggerScenarios":"Malformed chunks (None lines, negative indices) reaching _apply_update; unexpected None in new_content or chunks from hand-built PatchActions; regressions in helper functions raising arbitrary exceptions.","commonSituations":"Programmatic use of PatchCoder with custom-built actions; version mismatches after refactors; corrupt in-memory state after a failed parse is reused.","solutions":["Inspect the embedded exception message/type; if it's a TypeError/AttributeError, audit how the PatchAction and chunks were constructed","Rebuild actions via the parser (parse a full patch text) instead of constructing them manually","Report upstream if the actions came straight from parsed model output"],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"def actions_wellformed(actions) -> bool:\n    for a in actions:\n        if a.chunks is None or any(c is None for c in (a.chunks or [])):\n            return False\n        if a.type.name == \"ADD\" and not isinstance(a.new_content, str):\n            return False\n    return True","typeGuard":null,"tryCatchPattern":"try:\n    coder.apply_edits(edits)\nexcept ValueError as e:\n    if str(e).startswith(\"Unexpected error\"):\n        # capture full traceback — this is a bug, not a patch problem\n        log.exception(\"apply_edits internal failure\")\n    raise","preventionTips":["Never construct chunks/actions with None fields; reparse from patch text instead","Pin aider versions in automation so refactors don't shift internals","Keep full traceback on unexpected errors to distinguish bugs from patch mismatches"],"tags":["aider","patch","apply","unexpected-exception"],"backgroundTag":null,"analyzedSha":"5dc9490bb35f9729ef2c95d00a19ccd30c26339c","analyzedAt":"2026-08-15T05:40:10.498Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}