dify icon indicating copy to clipboard operation
dify copied to clipboard

VariableTruncator unnecessarily truncates strings that exactly fit the estimated budget

Open sergioperezcheco opened this issue 1 month ago • 3 comments

Self Checks

  • [x] I have read the Contributing Guide and Language Policy.
  • [x] This is only for bug report, if you would like to ask a question, please head to Discussions.
  • [x] I have searched for existing issues search for existing issues, including closed ones.
  • [x] I confirm that I am using English to submit this report, otherwise it will be closed.
  • [x] 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • [x] Please do not modify this template :) and fill in all the required fields.

Dify version

Source main at 1cbb6dc385878c950e2252f17f1954211fd1e763.

Cloud or Self Hosted

Self Hosted (Source). Reproduced with isolated backend unit tests, not a deployed instance.

Steps to reproduce

Run this through the backend Python environment:

from graphon.variables.segments import StringSegment
from services.variable_truncator import VariableTruncator

t = VariableTruncator(string_length_limit=10, max_size_bytes=10)
r = t.truncate(StringSegment(value="abcdefgh"))
print(t.calculate_json_size("abcdefgh"))
print(r.result.value, r.truncated)

mapping = {"value": ""}
budget = t.calculate_json_size("value") + t.calculate_json_size("")
print(VariableTruncator(max_size_bytes=budget).truncate_variable_mapping(mapping))

The first string has an estimated size of 10, including the two quote characters, and fits its allocated budget exactly. In the mapping example the remaining value budget equals the empty string's estimated size. _truncate_string currently checks < target_size, so equality goes through the ellipsis path in both cases.

I propose changing just that fit comparison to <=, with public-API regressions for exact and spare budgets and an over-budget control. This keeps the existing character-count estimator: it does not introduce UTF-8 byte accounting, repair overall mapping serialization accounting, or alter array truncation.

The original implementation in #25360 says the final size should not exceed the limits, and the public fallback activates only for > max_size_bytes. The existing test_exact_limit_string, already present before #33223, uses ten characters with a budget of ten: its estimated size is twelve, so its truncation expectation remains correct. #33223 fixed over-budget mapping flags and the StringSegment fallback; it did not change this equality comparison. Open #37193 and #39774 address array flag propagation, a different behavior that this proposal leaves alone.

This report follows the issue-first contribution process; it does not imply maintainer approval of the proposed change.

✔️ Expected Behavior

A string whose existing estimated size equals its allocated budget should be preserved with truncated=False. Strings exceeding that budget should still be truncated.

❌ Actual Behavior

The first example returns estimated size 10, then abcde... True. The mapping example replaces the empty string with ... and returns True, even though the original value fits its allocated budget.

On this exact source revision, the new public-API regression file returned 6 failed / 6 passed against unchanged production code. With the single comparison change, the existing truncator module and the new regression module returned 64 passed; targeted Ruff and format checks passed. These are verified local results retained from the preceding validation, not a new full-suite run. The earlier targeted Pyrefly check also reported zero diagnostics with an explicit existing venv interpreter.

No complete backend suite, deployment/UI, HTTP/SSE integration, provider invocation, cross-platform matrix, or remote CI was run. Unicode regression input only exercises the existing character-count approximation. The scope is the truncator's returned values and flags; this report does not claim loss of persisted workflow results or that Service API responses use this truncation path.

From Hermes Agent

sergioperezcheco avatar Oct 04 '26 10:10 sergioperezcheco

The code at that revision matches your diagnosis. _truncate_string returns the original value only when the estimated size is strictly less than the target, so a size equal to the target falls through to the "..." or prefix-plus-ellipsis path.

The mapping case takes the same path. In truncate_variable_mapping, the per-value budget is (budget - used_size) // remaining entries. With budget = size("value") + size(""), the empty string gets a budget of 2. Its size is also 2, so the < check fails and it becomes ... with truncated=True.

The regression tests should also cover one side effect. For a StringSegment, truncate() passes string_length_limit as the target size. With <=, a string whose JSON size equals the limit (for example 8 characters with a limit of 10) will be kept whole, where today it is cut to limit - 5 characters plus .... That matches your expected behavior, and the final fallback at > max_size_bytes already treats equality as fitting.

The existing test_exact_limit_string uses 10 characters with a target of 10. Its estimated size is 12, so it stays over budget and its expectation still holds with <=.

To reply, just mention @dosu.


Share context across your team and agents. Try Dosu.

Leave Feedback Learn about dify with Dosu

dosubot[bot] avatar Oct 04 '26 10:10 dosubot[bot]

This is an off-by-one truncation bug. Strings that exactly fit the estimated budget are being unnecessarily truncated, losing valid content.

The issue is likely a strict less-than comparison instead of less-than-or-equal. Change the condition from len(string) < budget to len(string) <= budget.

Also consider adding a small buffer to the budget estimation to account for tokenization variance.

belentani7 avatar Oct 05 '26 06:10 belentani7

Hi, I’d like to work on this issue. I plan to add regression tests for strings that exactly fit, have spare budget, and exceed the budget, then make the smallest change needed to preserve values that fit. Does this scope look good to you?

CHENZlHAO avatar Oct 15 '26 11:10 CHENZlHAO