Skip to content

[Due for payment 2025-11-26] [Due for payment 2025-11-17] [CRN-QA] report field initial value set to formula referencing itself #70775

Closed

Description

@neil-marcellini

Issue Reported by : Applause Internal Team

Action performed

  1. Create a workspace and expense report on the workspace
  2. Set the default report title to "Report field value {field:Test text}"
  3. Create a text report field on the policy named "Test text" with the initial value set to "initial"
  4. Update the initial value to "{field:Test text}"
  5. Open the initial value page again
  6. Delete the report field
  7. Open the policy expense chat

Expected result

  • Setting the initial value of a report field, or the value of a report field, to a text value which is a formula referencing the field itself, and therefore creating a circular reference, should result in an error and the new value should not be saved
    • Note: On Classic, setting the initial value of a report field to a valid formula makes the report field a "formula" type, and its value can not be manually changed on the report.
  • If a report field initial value is a formula that references itself, and it is already saved in the database, because it is currently allowed on Expensify Classic, then the type of the returned report field should be changed to "text" so that it is not computed

The initial value page is not blank, and when opening the policy expense chat the app does not crash

Actual result

The initial value page is blank, and the app crashes when opening the policy expense chat

490105214-64e7dfec-1f75-472e-92ae-1bbab24580e6.mp4

OldDot behavior

2025-10-01_08-10-53.mp4
Backend code for identifying circular references

First circular references are checked for the whole formula, but on the frontend you could check passing only one "part" such as {field:someField}, and no parent fields.

string Formula::compute(SQLite& db, const JSON::Value& reportJSON, const UserDefinedFieldFormula* formula,
                        map<int64_t, UserCache>* userCacheMap, map<string, PolicyCache>* policyCacheMap, map<int64_t, ReportCache>* reportCacheMap, const JSON::Value& transactionJSON, const bool preventDeprecatedFormulas)
{
    SDEBUG("[Formula::compute] defaultValue: " << formula->getDefaultValue().value());
    const auto parts = parse(formula->getFormula());

    const int64_t reportID = reportJSON.getIntMemberWithDefault("reportID", 0);
    if (hasCircularReferences(db, reportID, parts, {})) {
        SINFO("Formula has circular references, omitting");
        return "";
    }


bool Formula::hasCircularReferences(SQLite& db, int64_t reportID, const vector<unique_ptr<FormulaPart>>& parts, const vector<string>& parentFields)
{
    // Prevent excessive recursion depth that could cause stack overflow
    if (parentFields.size() > MAX_CIRCULAR_REFERENCE_DEPTH) {
        SHMMM("Circular reference depth exceeds maximum allowed", {{"depth", to_string(parentFields.size())}, {"maxDepth", to_string(MAX_CIRCULAR_REFERENCE_DEPTH)}});

        // Assume circular reference to prevent further recursion
        return true;
    }

    for (const auto& part : parts) {
        if (part->getType() != FormulaPart::TYPE_FIELD) {
            continue;
        }

        auto* fieldPart = static_cast<FieldPart*>(part.get());
        const optional<unique_ptr<UserDefinedField>>& field = fieldPart->getField(db, reportID);
        if (!field.has_value()) {
            continue;
        }

        auto* formulaField = dynamic_cast<UserDefinedFieldFormula*>(field.value().get());
        if (!formulaField) {
            continue;
        }

        const string fieldID = formulaField->getID();
        if (find(parentFields.begin(), parentFields.end(), fieldID) != parentFields.end()) {
            return true;
        }

        vector<string> newParentFields = parentFields;
        newParentFields.push_back(fieldID);
        if (formulaField->hasCircularReferences(db, reportID, newParentFields)) {
            return true;
        }
    }
    return false;
}



optional<unique_ptr<UserDefinedField>> FieldPart::getField(SQLite& db, int64_t reportID)
{
    if (fieldPath.size() == 0) {
        return nullopt;
    }

    string name = fieldPath[0];
    auto fieldID = UserDefinedField::createFromDatabaseData<UserDefinedField>(JSON::Value({{"name", STrim(name)}, {"type", UserDefinedField::UDF_TYPE_TEXT}}))->getID();
    auto udfs = Report::getUserDefinedFields(db, reportID);

    for (auto& udf : udfs) {
        if (udf->getID() == fieldID) {
            return make_optional(move(udf));
        }
    }

    return nullopt;
}
Issue OwnerCurrent Issue Owner: @sonialiap

Activity

  1. added
    External
    Daily
    Help Wanted
    on Sep 17, 2025
  2. melvin-bot commented on Sep 17, 2025

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @DylanDylann (External)

  3. mukhrr commented on Sep 18, 2025

    @mukhrr
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2025-09-18 01:57:45 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    After setting report field initial value to "{field:Test text}" app crashes

    What is the root cause of that problem?

    It's crashish as BE is sending type as "formula" when inital value is set to "{field:Test text}" even if type is "text"

    Image

    Thus, this function is causing crash:

    function getReportFieldTypeTranslationKey(reportFieldType: PolicyReportFieldType): TranslationPaths {
    const typeTranslationKeysStrategy: Record<string, TranslationPaths> = {
    [CONST.REPORT_FIELD_TYPES.TEXT]: 'workspace.reportFields.textType',
    [CONST.REPORT_FIELD_TYPES.DATE]: 'workspace.reportFields.dateType',
    [CONST.REPORT_FIELD_TYPES.LIST]: 'workspace.reportFields.dropdownType',
    };
    return typeTranslationKeysStrategy[reportFieldType];
    }

    What changes do you think we should make in order to solve the problem?

    We should give fallback text type to getReportFieldTypeTranslationKey and getReportFieldAlternativeTextTranslationKey:

    return typeTranslationKeysStrategy[reportFieldType] || typeTranslationKeysStrategy[CONST.REPORT_FIELD_TYPES.TEXT];

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    N/A

    What alternative solutions did you explore? (Optional)

    But I think still root cause is from backend.

  4. NJ-2020 commented on Sep 18, 2025

    @NJ-2020
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2025-09-18 10:30:22 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Report field formulas: Report name is not updated to “Report field value {field:Test text}” and app crash observed

    What is the root cause of that problem?

    When we update the initial value field into {field:Test text}, the BE update the field type based on the provided initial value, int this case, the BE update from text into >> formula
    Image
    But since we don't have formula keys here, and when we try to retrieve the based on the report field type, it will return undefined here since it doesn't exist which cause the translate localize to throw an error

    rightLabel: Str.recapitalize(translate(getReportFieldTypeTranslationKey(reportField.type))),

    function getReportFieldTypeTranslationKey(reportFieldType: PolicyReportFieldType): TranslationPaths {
    const typeTranslationKeysStrategy: Record<string, TranslationPaths> = {
    [CONST.REPORT_FIELD_TYPES.TEXT]: 'workspace.reportFields.textType',
    [CONST.REPORT_FIELD_TYPES.DATE]: 'workspace.reportFields.dateType',
    [CONST.REPORT_FIELD_TYPES.LIST]: 'workspace.reportFields.dropdownType',
    };
    return typeTranslationKeysStrategy[reportFieldType];
    }

    throw new Error(`${path} was not found in the ${locale} locale`);

    So instead of passing correct value like this:

    Str.recapitalize(translate('Text' || 'Date' || 'List'))

    we pass undefined which cause an error/crash

    Str.recapitalize(translate(undefined)) // << formula is not exists

    What changes do you think we should make in order to solve the problem?

    Based right here, we need to add new validation check here whether if the report field initial value is containing formula pattern or not

    Initial value check validation

    function WorkspaceCreateReportFieldsPage({
        policy,
        route: {
            params: {policyID},
        },
    }: CreateReportFieldsPageProps) {
        ...
        const validateForm = useCallback(
            (values: FormOnyxValues<typeof ONYXKEYS.FORMS.WORKSPACE_REPORT_FIELDS_FORM>): FormInputErrors<typeof ONYXKEYS.FORMS.WORKSPACE_REPORT_FIELDS_FORM> => {
                const {name, type, initialValue: formInitialValue} = values;
                const errors: FormInputErrors<typeof ONYXKEYS.FORMS.WORKSPACE_REPORT_FIELDS_FORM> = {};
    
                ...
    
                // Include formula value check here
                if (type === CONST.REPORT_FIELD_TYPES.TEXT && containsFormulaPattern(formInitialValue)) {
                    errors[INPUT_IDS.INITIAL_VALUE] = translate('workspace.reportFields.formulaError');
                }
    
                return errors;
            },
            [availableListValuesLength, policy?.fieldList, translate],
        );
        ...
    }

    Updating report field initial value

    function ReportFieldsInitialValuePage({
        policy,
        route: {
            params: {policyID, reportFieldID},
        },
    }: ReportFieldsInitialValuePageProps) {
        ...
        const validateForm = useCallback(
            (values: FormOnyxValues<typeof ONYXKEYS.FORMS.WORKSPACE_REPORT_FIELDS_FORM>): FormInputErrors<typeof ONYXKEYS.FORMS.WORKSPACE_REPORT_FIELDS_FORM> => {
                const {initialValue: formInitialValue} = values;
                const errors: FormInputErrors<typeof ONYXKEYS.FORMS.WORKSPACE_REPORT_FIELDS_FORM> = {};
    
                if (reportField?.type === CONST.REPORT_FIELD_TYPES.TEXT && containsFormulaPattern(formInitialValue)) {
                    errors[INPUT_IDS.INITIAL_VALUE] = translate('workspace.reportFields.formulaError');
                }

    Updating report field value inside expense report

    function EditReportFieldTextPage({fieldName, onSubmit, fieldValue, isRequired, fieldKey}: EditReportFieldTextPageProps) {
        ...
    
        const validate = useCallback(
            (values: FormOnyxValues<typeof ONYXKEYS.FORMS.REPORT_FIELDS_EDIT_FORM>) => {
                const errors: FormInputErrors<typeof ONYXKEYS.FORMS.REPORT_FIELDS_EDIT_FORM> = {};
                const inputValue = values[fieldKey].trim();
                if (isRequired && inputValue === '') {
                    errors[fieldKey] = translate('common.error.fieldRequired');
                }
    
                // Formula value validation check
                if (containsFormulaPattern(inputValue)) {
                    errors[fieldKey] = translate('workspace.reportFields.formulaError');
                }
    
                return errors;
            },
            [fieldKey, isRequired, translate],
        );

    Test branch

    Result

    Screen.Recording.2025-09-29.at.09.53.14.mp4

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    N/A

    What alternative solutions did you explore? (Optional)

    N/A

  5. NJ-2020 commented on Sep 18, 2025

    @NJ-2020
    Contributor

    Note: I'm unsure if we should update the expense report name optimistically when updating the report field

    1. Set the report field to “updated”
    2. Verify the report name is updated to “Report field value updated”

    It seems we're specifically addressing the {field: Test text} report name update bug error/crash rather than also updating the expense name optimistically. Also, I can't preview the attached video. Thanks

    Image
  6. DylanDylann commented on Sep 18, 2025

    @DylanDylann
    Contributor

    Testing account configured for "Custom report formula" by running the snippets

    Does anyone know how to enable this configuration?

  7. NJ-2020 commented on Sep 18, 2025

    @NJ-2020
    Contributor

    @DylanDylann Here is the configuration docs

    Source: #68803

  8. DylanDylann commented on Sep 18, 2025

    @DylanDylann
    Contributor

    @NJ-2020 Thanks for your reference

  9. DylanDylann commented on Sep 18, 2025

    @DylanDylann
    Contributor

    @neil-marcellini could you upload the video on the OP again? It will help us determine the bug correctly

  10. NJ-2020 commented on Sep 18, 2025

    @NJ-2020
    Contributor

    Proposal updated

    • Added new RCA/solution for this bug
    • Update result video
  11. neil-marcellini commented on Sep 18, 2025

    @neil-marcellini
    ContributorAuthor

    @neil-marcellini could you upload the video on the OP again? It will help us determine the bug correctly

    Oh right, sorry about that. I transferred this from our internal repository and forgot that the video link wouldn't work. It is re-uploaded now.

  12. 96 remaining items

  13. melvin-bot commented on Dec 2, 2025

    @melvin-bot

    Triggered auto assignment to @sonialiap (Bug), see https://stackoverflow.com/c/expensify/questions/14418 for more details. Please add this bug to a GH project, as outlined in the SO.

  14. added
    Daily
    and removed
    Weekly
    on Dec 2, 2025
  15. neil-marcellini commented on Dec 2, 2025

    @neil-marcellini
    ContributorAuthor

    Hi @sonialiap would you please handle payment?

  16. sonialiap commented on Dec 3, 2025

    @sonialiap
    Contributor

    @neil-marcellini looks like the PR was submitted by NJ-2020 so the payees are NJ-2020 and DylanDylann, is that correct?

  17. sonialiap commented on Dec 4, 2025

    @sonialiap
    Contributor

    Payment summary:
    @DylanDylann $250 please request in NewDot
    @NJ-2020 $250 offer sent in upwork - paid

  18. NJ-2020 commented on Dec 4, 2025

    @NJ-2020
    Contributor

    @sonialiap Thanks, accepted!

  19. DylanDylann commented on Dec 5, 2025

    @DylanDylann
    Contributor

    BugZero Checklist:

    • [Contributor] The offending PR has been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      Link to comment: New improvement

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion:

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    • [BugZero Assignee] Create a GH issue for creating/updating the regression test once above steps have been agreed upon.

      Link to issue: https://github.com/Expensify/Expensify/issues/575550

    Regression Test Proposal

    Test:

    1. Create a workspace if needed
    2. Go to workspace settings, Reports, enable report fields if needed

    Case 1: Self Reference

    1. Create new report field named "A"
    2. Attempt to set it's initial value to "{field:A}"
    3. Verify an error is displayed and you can't save that value

    Case 2: 2 circular/references

    1. Create new report field named "A"
    2. Set it's initial value to "{field:B}" (make sure {field:B} or field B is not created yet)
    3. Verify you can save/create the field
    4. Create new report field named "B"
    5. Attempt to set it's initial value to "{field:A}"
    6. Verify an error is displayed and you can't save that value

    Case 3: More than 2 circular/references

    1. Create new report field named "A"
    2. Set it's initial value to "{field:B}" (make sure {field:B} or field B is not created yet)
    3. Verify you can save/create the field
    4. Create new report field named "B"
    5. Set it's initial value to "{field:C}" (make sure {field:C} or field C is not created yet)
    6. Create new report field named "C"
    7. Attempt to set it's initial value to "{field:A}"
    8. Verify an error is displayed and you can't save that value

    Case 4: No references

    1. Create new report field named "A"
    2. Set it's initial value to "{field:B}" (make sure {field:B} is created and the default/initial value is set to empty > "" or no formula circular field)
    3. Verify you can save/create the field

    Case 5: Report field value / report expense

    1. Go to workspace expenses chat
    2. Select/Open any report
    3. Edit the report field value
    4. Type formula value that references itself/circular reference i.e A, A > A, A > B > A
    5. Verify an error is displayed and you can't save that value

    Do we agree 👍 or 👎

  20. JmillsExpensify commented on Jan 5, 2026

    @JmillsExpensify
    Contributor

    $250 approved for @DylanDylann

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentBugDailyDesignInternal

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions