Excessive Recursion in modelFromJSON Causes Stack Overflow ( Parser Depth Handling Bug )
Excessive Recursion in modelFromJSON Causes Stack Overflow ( Parser Depth Handling Bug )
System information
- Have I written custom code: Yes (minimal PoC)
- OS Platform: Windows 11
- Mobile device: N/A
- TensorFlow.js installed from: npm
- TensorFlow.js version:
@tensorflow/[email protected] - Browser version: N/A (Node.js execution)
- TensorFlow.js Converter Version: Not applicable
- Node.js runtime: v22.18.0
Describe the current behavior
When calling:
tf.models.modelFromJSON(...)
with a model configuration containing extremely deep nested "config" objects, the parser crashes with:
RangeError: Maximum call stack size exceeded
The model loader recursively walks through the configuration without:
- enforcing a maximum nesting depth
- validating input structure
- switching to an iterative-safe traversal
This results in a JavaScript stack overflow during JSON model parsing.
This is a robustness bug affecting model loading of malformed or accidentally nested config structures.
Describe the expected behavior
The parser should gracefully reject unreasonably deep configurations.
Expected safeguards:
- Detect excessive nesting (e.g., > 1000 levels)
- Abort with a clear error message such as:
“Model configuration depth exceeds supported limit.” - Avoid triggering recursive stack overflow.
This improves resilience when handling corrupted, user-generated, or automated model configs.
Standalone code to reproduce the issue
Save as reproduce_tfjs_parser_depth_bug.js:
const tf = require('@tensorflow/tfjs');
async function checkParserStability() {
console.log("[*] Testing Parser Depth Limits...");
const depth = 5000; // large enough to exceed JS call stack
let nestedConfig = { layers: [] };
let current = nestedConfig;
// Generate deeply nested `"config"` chain
for (let i = 0; i < depth; i++) {
current.config = { layers: [] };
current = current.config;
}
const modelStructure = {
"modelTopology": {
"class_name": "Sequential",
"config": nestedConfig
}
};
try {
await tf.models.modelFromJSON(modelStructure);
} catch (err) {
console.log("Status:", err.message);
}
}
checkParserStability();
How to run
node reproduce_tfjs_parser_depth_bug.js
Observed output
[*] Testing Parser Depth Limits...
Status: Maximum call stack size exceeded
Depth values >2000–3000 consistently trigger the same failure.
Explanation
The underlying issue is unbounded recursive descent in the model loader's configuration parsing.
Because JavaScript engines (V8 on Node.js) impose strict call-stack limits, this leads to:
- Call stack exhaustion
- Immediate crash inside
modelFromJSON - No graceful recovery path
While not a security issue, this is a correctness and stability bug for any workflow that processes:
- Auto-generated configs
- Third-party model JSON
- Machine-generated nested structures
- Corrupted or malformed models
Adding a depth-checking guard or iterative parsing would prevent this runtime crash.
Other info / logs
- Not browser-specific (reproduces in Node.js)
- No native memory access; pure JS error
Conclusion
The modelFromJSON parser lacks a recursion depth limit, making the library vulnerable to uncontrolled recursion (CWE-674).
This allows malformed or deeply nested configurations to exhaust the JavaScript call stack, causing an immediate process crash.
To ensure reliability and prevent runtime termination, the parser should:
- Implement a maximum nesting depth guard, or
- Use an iterative traversal strategy instead of deep recursion.
Adding these safeguards would prevent call-stack crashes and improve TensorFlow.js robustness when handling complex or malformed inputs.
Hi @amadhan882 , I have tested the replication code and faced the same issue.Could you please provide the use case/scenario where you need these stack of layers. Thank you.
Hi @avmohansai,
Thank you for confirming the behavior.
Regarding the use case: while a typical neural network would not require thousands of nested layers, the concern here is less about legitimate model complexity and more about robustness when handling malformed or externally provided JSON.
A few practical scenarios where this could matter:
Service Stability: In Node.js environments that process third-party or dynamically generated models, a deeply nested structure can trigger an unhandled RangeError, terminating the process instead of returning a controlled validation error.
Defensive Parsing: Since the current behavior relies on the JavaScript engine’s stack limits, introducing an explicit recursion depth guard (or using an iterative traversal strategy) would provide more predictable and graceful failure handling across environments.
Rather than allowing the runtime to throw a stack overflow error, the parser could proactively detect excessive nesting and return a clear Invalid model configuration message.
Happy to help test any proposed safeguard or adjustments.
Hi @amadhan882 , Thanks for the reply and that's a great point-outs. As per my understanding this is not related to tfjs and a limitation from the language itself. Thank you.
Hi @avmohansai,
Thanks for the response. While I agree it's a JS engine limitation, a library like TFJS should ideally handle this gracefully rather than letting the entire process crash with a RangeError.
Implementing a simple recursion depth guard (e.g., max 100 levels) would prevent an unhandled crash and provide a better developer experience. It turns an 'uncontrolled crash' into a 'validated error'
Hi @amadhan882, We appreciate your feedback regarding this issue. we will file a bug internally.
Hi @amadhan882, Thank you for bringing this to our attention and for providing a comprehensive overview. We appreciate the time you invested in creating this issue.
Currently, our internal development team is concentrated on other scheduled milestones, so we cannot prioritize this task immediately. However, we would love to see this move forward as a community-led effort.
If you’d like to submit a fix, please fork the repo and open a PR following the TensorFlow Contribution Guidelines, Tfjs Contributions and be sure to link this issue in your PR to avoid duplicate work, kindly leave a comment here if you plan to take this on.
Thank you again for your interest and time.
Hi @amadhan882, Thank you for opening this issue. Since this issue has been open for a long time, we are closing this issue for now. If this is still relevant and you would like to work on it, please feel free to reopen the issue or submit a pull request referencing it. Thank you for your understanding.