Skip to content

Commit ebd9d9d

Browse files
authored
Add fast-fail detection for slow formula generation (#593)
1 parent 47cf19d commit ebd9d9d

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
## [Unreleased]
22

3+
### Enhancements
4+
5+
* Improve formula generation performance by imposing tighter limits on variant simplification
6+
37
### Bugfixes
48

59
* Fix parsing error during stats generation

src/form/variant.cpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ bool VariantsManager::update(Variant new_variant) {
3939
return false;
4040
}
4141
const auto num_terms = new_variant.definition.numTerms();
42-
if (num_terms > 500) { // magic number
42+
if (num_terms > 200) { // limit term count to reduce complexity
4343
Log::get().debug("Skipping variant with " + std::to_string(num_terms) +
4444
" terms");
4545
return false; // too many terms
@@ -49,6 +49,10 @@ bool VariantsManager::update(Variant new_variant) {
4949
// return false;
5050
// }
5151
auto& vs = variants[new_variant.func];
52+
// limit number of variants per function to reduce O(n^4) complexity
53+
if (vs.size() >= 20) {
54+
return false;
55+
}
5256
// prevent rapid increases of variant sizes
5357
if (!std::all_of(vs.begin(), vs.end(), [new_variant](const Variant& v) {
5458
return v.used_funcs.size() + 1 >= new_variant.used_funcs.size();
@@ -196,7 +200,9 @@ bool simplifyFormulaUsingVariants(
196200
Formula& formula, std::map<std::string, int64_t>& num_initial_terms) {
197201
VariantsManager manager(formula, num_initial_terms);
198202
bool found = false;
199-
while (manager.numVariants() < 200) { // magic number
203+
size_t iterations = 0;
204+
while (manager.numVariants() < 100 && iterations < 50) { // tighter limits
205+
iterations++;
200206
if (findVariants(manager)) {
201207
found = true;
202208
} else {

0 commit comments

Comments
 (0)