Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/server-dependency-depth-linear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"posthog-server": patch
---

Keep flag dependency evaluation linear for dependency chains deeper than 100. A flag result computed while the depth limit or the evaluation budget cut off a dependency below it is remembered with the depth it was reached at, until a flag cut off below it is cached. A value is kept per depth and reused only at that depth. A failure is kept at the shallowest depth that failed and reused there or deeper, where it stays conservatively inconclusive and defers to the server. So a shorter path, or a path that can now finish within the limit, evaluates the flag again instead of reading a result that holds only on the other path, and a chain reached from different depths isn't walked again on every reference. Caching unrelated flags doesn't discard these results. Cycles are still never cached.
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,55 @@ internal class FlagEvaluationContext(
/** How many flag dependencies this evaluation has computed, bounded since path-dependent results aren't cached. */
var dependencyEvaluations: Int = 0

/** How many times a cycle cut off a dependency. A result computed while this grew isn't cached. */
var cycleHits: Int = 0

/** How many times the depth limit or the evaluation budget cut off a dependency. */
var depthLimitHits: Int = 0

/**
* Values of flags computed while the depth limit or the budget cut off a dependency below them, by flag key
* and the depth that reached the flag. Such a value depends on that depth, so it's kept out of the evaluation
* cache and reused only at the same depth.
*/
val depthLimitedValues: MutableMap<Pair<String, Int>, DepthLimitedValue> = mutableMapOf()

/**
* How many times a dependency was cut off by the depth limit, a cycle or the evaluation budget. A
* result computed while this grew depends on the path that reached it, so it isn't cached.
* Failures of flags that were inconclusive while the depth limit or the budget cut off a dependency below
* them, by flag key, with the shallowest depth that failed. They're kept out of the evaluation cache.
*/
var pathDependentFailures: Int = 0
val depthLimitedFailures: MutableMap<String, DepthLimitedFailure> = mutableMapOf()

/**
* Flags the depth limit or the budget cut off, or with a result in [depthLimitedValues] or
* [depthLimitedFailures]. Caching one of them, a value or a failure, bumps [resolutionVersion].
*/
val depthLimitedKeys: MutableSet<String> = mutableSetOf()

/**
* Bumped when a flag in [depthLimitedKeys] is cached, so a depth-limited result computed before can
* now resolve further. Caching any other flag doesn't change a depth-limited result.
*/
var resolutionVersion: Int = 0
}

/**
* A flag value computed at one depth while the depth limit or the budget cut off a dependency below it. It's
* reused only at that depth and while [resolutionVersion], read before the flag was evaluated, is current:
* deeper, it can become inconclusive, and shallower, it can change.
*/
internal class DepthLimitedValue(
val resolutionVersion: Int,
val value: Any?,
)

/**
* A flag [failure] at [entryDepth] while the depth limit or the budget cut off a dependency below it. It's
* reused from [entryDepth] or deeper, where more of the chain is cut off, while [resolutionVersion], read
* before the flag was evaluated, is current.
*/
internal class DepthLimitedFailure(
val entryDepth: Int,
val resolutionVersion: Int,
val failure: InconclusiveMatchException,
)
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import java.util.regex.PatternSyntaxException
internal class FlagEvaluator(
private val config: PostHogConfig,
private val propertyMatchingVersion: Int? = null,
// Lowered only by tests, to reach the limit with short chains.
private val maxDependencyDepth: Int = MAX_DEPENDENCY_DEPTH,
) {
companion object {
private const val LONG_SCALE = 0xFFFFFFFFFFFFFFF.toDouble()
Expand Down Expand Up @@ -1961,9 +1963,13 @@ internal class FlagEvaluator(
}

/**
* Computes the dependency [depFlagKey] and caches its result, or its failure as null, unless it was
* cut off on this path by the depth limit, a cycle or the evaluation budget: a shallower reference
* later in the same evaluation must still be able to resolve it.
* Computes the dependency [depFlagKey] and caches its result, or its failure as null. A result computed
* while a cycle cut off a dependency below it isn't kept. One computed while the depth limit or the
* evaluation budget cut off a dependency below it is kept apart with the depth it was reached at, until a
* flag cut off below it is cached. A value is kept per depth and reused only at that depth, where evaluating
* the flag again would give the same result. A failure is kept at the shallowest depth that failed and
* reused there or deeper, a conservative approximation that keeps the work linear: deeper, more of the chain
* is cut off, so the flag stays inconclusive and defers to the server.
*/
private fun computeDependency(
depFlagKey: String,
Expand All @@ -1978,49 +1984,107 @@ internal class FlagEvaluator(
"Cannot evaluate flag dependency '$depFlagKey' - flag not found in local flags",
PostHogUnresolvedFlagReason.UNSUPPORTED_DEFINITION,
)
val cutOff =
val entryDepth = context.dependencyDepth
// A malformed chain that leads back to a flag being evaluated can't recurse.
if (depFlagKey in context.inProgressFlags) {
context.cycleHits++
throw InconclusiveMatchException(
"Flag dependency '$depFlagKey' leads back to itself",
PostHogUnresolvedFlagReason.UNRESOLVED_DEPENDENCY,
)
}
val depthCutOff =
when {
// A malformed chain that leads back to a flag being evaluated can't recurse.
depFlagKey in context.inProgressFlags -> "Flag dependency '$depFlagKey' leads back to itself"
// Deeper chains are inconclusive, so a long chain can't exhaust the stack.
context.dependencyDepth >= MAX_DEPENDENCY_DEPTH ->
"Flag dependency chain for '$depFlagKey' is deeper than $MAX_DEPENDENCY_DEPTH"
entryDepth >= maxDependencyDepth ->
"Flag dependency chain for '$depFlagKey' is deeper than $maxDependencyDepth"
context.dependencyEvaluations >= MAX_DEPENDENCY_EVALUATIONS ->
"Evaluated more than $MAX_DEPENDENCY_EVALUATIONS flag dependencies"
else -> null
}
if (cutOff != null) {
context.pathDependentFailures++
throw InconclusiveMatchException(cutOff, PostHogUnresolvedFlagReason.UNRESOLVED_DEPENDENCY)
if (depthCutOff != null) {
context.depthLimitHits++
context.depthLimitedKeys.add(depFlagKey)
throw InconclusiveMatchException(depthCutOff, PostHogUnresolvedFlagReason.UNRESOLVED_DEPENDENCY)
}
// Reusing a failure at the same or deeper depth stays conservatively inconclusive and keeps the work
// linear; a value is reused only at the exact same depth, where re-evaluation would give the same result.
val depthLimitedValue = context.depthLimitedValues[depFlagKey to entryDepth]
if (depthLimitedValue != null && depthLimitedValue.resolutionVersion == context.resolutionVersion) {
context.depthLimitHits++
return dependencyValue(depFlagKey, depthLimitedValue.value)
}
val depthLimitedFailure = context.depthLimitedFailures[depFlagKey]
if (depthLimitedFailure != null &&
depthLimitedFailure.resolutionVersion == context.resolutionVersion &&
entryDepth >= depthLimitedFailure.entryDepth
) {
context.depthLimitHits++
throw depthLimitedFailure.failure
}

context.dependencyEvaluations++
val pathDependentFailuresBefore = context.pathDependentFailures
val cycleHitsBefore = context.cycleHits
val depthLimitHitsBefore = context.depthLimitHits
val resolutionVersionBefore = context.resolutionVersion
context.dependencyDepth++
val value: Any?
try {
val value = computeFlag(depFlag, context, cohortProperties, flagsByKey, evaluationCache)
if (context.pathDependentFailures == pathDependentFailuresBefore) {
evaluationCache[depFlagKey] = value
}
return value
?: throw InconclusiveMatchException(
"Flag dependency '$depFlagKey' evaluated to no value",
value = computeFlag(depFlag, context, cohortProperties, flagsByKey, evaluationCache)
} catch (e: InconclusiveMatchException) {
val failure =
InconclusiveMatchException(
"Cannot evaluate flag dependency '$depFlagKey': ${e.message}",
PostHogUnresolvedFlagReason.UNRESOLVED_DEPENDENCY,
e,
)
} catch (e: InconclusiveMatchException) {
if (context.pathDependentFailures == pathDependentFailuresBefore) {
evaluationCache[depFlagKey] = null
if (context.cycleHits == cycleHitsBefore) {
if (context.depthLimitHits == depthLimitHitsBefore) {
cacheDependency(depFlagKey, null, evaluationCache, context)
} else {
// A failure stored for this flag wasn't reused here, so it's from another version or deeper.
context.depthLimitedFailures[depFlagKey] = DepthLimitedFailure(entryDepth, resolutionVersionBefore, failure)
context.depthLimitedKeys.add(depFlagKey)
}
}
throw InconclusiveMatchException(
"Cannot evaluate flag dependency '$depFlagKey': ${e.message}",
PostHogUnresolvedFlagReason.UNRESOLVED_DEPENDENCY,
e,
)
throw failure
} finally {
context.dependencyDepth--
}
if (context.cycleHits == cycleHitsBefore) {
if (context.depthLimitHits == depthLimitHitsBefore) {
cacheDependency(depFlagKey, value, evaluationCache, context)
} else {
context.depthLimitedValues[depFlagKey to entryDepth] = DepthLimitedValue(resolutionVersionBefore, value)
context.depthLimitedKeys.add(depFlagKey)
}
}
return dependencyValue(depFlagKey, value)
}

private fun cacheDependency(
depFlagKey: String,
value: Any?,
evaluationCache: MutableMap<String, Any?>,
context: FlagEvaluationContext,
) {
evaluationCache[depFlagKey] = value
// A depth-limited result that ran out of depth at this flag may now resolve further.
if (context.depthLimitedKeys.remove(depFlagKey)) {
context.resolutionVersion++
}
}

private fun dependencyValue(
depFlagKey: String,
value: Any?,
): Any =
value
?: throw InconclusiveMatchException(
"Flag dependency '$depFlagKey' evaluated to no value",
PostHogUnresolvedFlagReason.UNRESOLVED_DEPENDENCY,
)

/**
* Check if the actual flag value matches the expected dependency value
*
Expand Down
Loading