ARC-82Required
Limit how deep code recurses on input
Every recursive function that walks outside input stops at a fixed depth, such as 64 levels, and raises a typed error. Input never decides how deep the stack grows.
How to do it
A JSON body with 100,000 nested brackets, a deep folder tree or a reply chain of a million comments overflows the stack of naive recursion. CWE-674 lists the result as CPU, memory and stack used up, which crashes the process. Pass the depth down and check it at the top of each call. Or walk the structure with a loop and an explicit stack, capped like any growing collection. Cap the size of the request first, as Cap the size of every request and answer says. Catch the depth error where input is parsed at the boundary, and answer with a client error.
Examples
TypeScript example
const MAX_DEPTH = 64;
export class ThreadTooDeep extends Error {}
export function countReplies(comment: Comment, depth = 0): number {
if (depth > MAX_DEPTH) throw new ThreadTooDeep(`Thread deeper than ${MAX_DEPTH} levels`);
return comment.replies.reduce((sum, reply) => sum + 1 + countReplies(reply, depth + 1), 0);
}
Python example
MAX_DEPTH = 64
class ThreadTooDeep(ValueError):
pass
def count_replies(comment: Comment, depth: int = 0) -> int:
if depth > MAX_DEPTH:
raise ThreadTooDeep(f"Thread deeper than {MAX_DEPTH} levels")
return sum(1 + count_replies(reply, depth + 1) for reply in comment.replies)
How to check
For each recursive walker, a test passes input nested one level past the limit and gets the typed error. A test with 100,000 levels returns the error in under a second, and the process keeps serving.
Sources
Related rules
- ARC-34 Cap every collection that grows with use in Clean code and architecture
- API-93 Cap the size of every request body in API design
- ARC-53 Parse input once at the boundary in Clean code and architecture
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/errors-and-nulls/recursion-depth-limit">Agent Wranglers clean code and architecture playbook</a>. In code you write, add a comment next to it with the same link.