App icon indicating copy to clipboard operation
App copied to clipboard

[$175] A failed move to another report is undone silently and leaves an empty $0 report

Open mountiny opened this issue 2 weeks ago • 34 comments

Part of https://github.com/Expensify/App/issues/106153 (receipt retention). Found by @adhorodyski.

Problem

When a move of an expense to another report fails, the expense goes back to its old report. The app shows no error, and an empty $0 report stays behind.

Impact

  • Severity: P2
  • About 170 failed moves a day.

Code

Related pull requests

Expected behavior

A failed move shows an error on the expense. The app removes the empty report it created.

Issue OwnerCurrent Issue Owner: @elirangoshen
Upwork Automation - Do Not Edit

mountiny avatar Nov 16 '26 04:11 mountiny

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

Job added to Upwork: https://www.upwork.com/jobs/~022122192342223165070

Proposal

What is the root cause of that problem?

Medium confidence: Failed moves restore the expense without adding a fallback error. Separately, creating the destination and moving the expense are independent requests, so a failed move does not undo successful report creation.

Code evidence and limitations

Alternative checked: Server responses can supply their own errors through onyxData; therefore, not every rejection is necessarily silent (OnyxUpdates.ts:74–111).

These findings explain the reported symptoms when creation succeeds and the subsequent move fails without a server-supplied error. They do not establish why the move was rejected. Production logs were unavailable, the reported ~170 failures/day was not independently verified, and no browser reproduction was performed.

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

Escalate the complete fix to an internal engineer for server-side lifecycle review. The required behavior is a visible failure on the restored expense plus safe, persistent cleanup of a destination created exclusively for that failed move.

An App-only removal from local state would hide, not delete, a persisted report. Existing report deletion can also unreport transactions, and its inspected request has no “only if still empty” guard (Report/index.ts:7548–7561, 7939–7946). Guaranteed cleanup therefore needs backend coordination, not an unverified App-only deletion.

Validation should cover successful creation followed by failed movement, existing destinations, concurrent additions, successful retry, and persistence after reload.

What alternative solutions did you explore? (Optional)

Deleting every empty destination is unsafe: it may predate the move or have acquired other content. A visible error alone addresses the silent rollback but leaves the empty-report symptom unresolved.

Related work


Next Steps for Contributor+ team:
Internal engineering review is required before accepting implementation.
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106962) to create a draft PR once an App-scoped plan is confirmed.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Nov 16 '26 04:11 MelvinBot

Proposal

What is the root cause of that problem?

There are two distinct root causes contributing to this behavior:

  1. Silent transaction move failure: In src/libs/actions/Transaction.ts (changeTransactionsReport, lines 1212–1225), when the ChangeTransactionsReport API command fails, failureData reverts the transaction's reportID, comment, and currency/amount values back to their pre-move state:
failureData.push({
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
    value: {
        reportID: transaction.reportID,
        comment: transaction.comment,
        originalAmount: transaction.originalAmount,
        originalCurrency: transaction.originalCurrency,
        ...(shouldClearAmount && {pendingAction: transaction.pendingAction ?? null}),
        ...(shouldClearAmount && {convertedAmount: transaction.convertedAmount}),
        ...(shouldClearAmount && {convertedTaxAmount: transaction.convertedTaxAmount}),
    },
});

Unlike other money request mutations (e.g. changeTransactionsToAutomaticReport in Transaction.ts:2290 or UpdateMoneyRequest.ts), failureData does not set errors on the transaction object. Therefore, when the server rejects the move request, the expense is moved back to the original report with zero visual feedback or Red Brick Road (RBR) indicator.

  1. Empty destination report lingering after rollback: When moving an expense via the "Create report" option (createReportForPolicy in src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts:220–239), an optimistic report is created via createNewReport (WRITE_COMMANDS.CREATE_APP_REPORT), followed immediately by changeTransactionsReport (WRITE_COMMANDS.CHANGE_TRANSACTIONS_REPORT). In Transaction.ts:1870–1916, failureData reverts the destination report's total, unheldTotal, and transactionCount. However, because the destination report itself was optimistically generated for this move, rolling back the totals leaves an empty, unlinked report with $0 total in Onyx (ONYXKEYS.COLLECTION.REPORT) and the LHN/search views, instead of cleaning it up as done for selfDMReport in Transaction.ts:1038–1055.

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

  1. Surface error on the transaction upon move failure: In src/libs/actions/Transaction.ts inside changeTransactionsReport:
  • In optimisticData, set errors: null on each moving transaction to clear any previous transient errors.
  • In failureData (line 1215), populate errors on each transaction using ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage') (or a specific translation key for move failure). This ensures that if the move request fails, an error banner is displayed directly on the restored expense card.
  1. Clean up newly created destination reports on move failure:
  • Accept an optional isNewReport?: boolean parameter in ChangeTransactionsReportProps (or inspect newReport?.pendingFields?.createReport === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD).
  • When useReportPickerActions.ts creates a report via createReportForPolicy and delegates to handleRegularReportSelection, pass isNewReport: true.
  • In changeTransactionsReport, when isNewReport is true, add rollback entries to failureData to remove the empty destination report:
if (isNewReport) {
    failureData.push(
        {
            onyxMethod: Onyx.METHOD.SET,
            key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
            value: null,
        },
        {
            onyxMethod: Onyx.METHOD.SET,
            key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
            value: null,
        },
        {
            onyxMethod: Onyx.METHOD.SET,
            key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${reportID}`,
            value: null,
        },
    );
    if (newReport?.parentReportID && newReport?.parentReportActionID) {
        failureData.push({
            onyxMethod: Onyx.METHOD.MERGE,
            key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${newReport.parentReportID}`,
            value: {
                [newReport.parentReportActionID]: null,
            },
        });
    }
}

This mirrors the existing optimistic cleanup pattern in Transaction.ts:1038–1055 and DeleteReport.ts, cleanly removing the $0 empty report from local state if the move cannot be completed.

What alternative solutions did you explore? (Optional)

  • We explored calling deleteAppReport unconditionally for any empty destination report on failure. However, an existing user report may legitimately have had 0 transactions prior to the move attempt; deleting it would destroy pre-existing user data. Restricting report removal specifically to isNewReport (reports instantiated during that move session) guarantees safe cleanup without side effects.

Contributor Details:

  • Email: [email protected]
  • Upwork Profile: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 16 '26 05:11 kevinjosh10

Proposal

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

When moving an expense to another report (ChangeTransactionsReport) fails:

  1. failureData silently moves the expense back to its original report without setting any error on the transaction, so the user sees no error banner or Red Brick Road (RBR) indicator explaining why the move was undone.
  2. When the user chose "Create report" to move the expense into a newly created report, createNewReport (WRITE_COMMANDS.CREATE_APP_REPORT) succeeds on the server first, and when the subsequent ChangeTransactionsReport request fails, rolling back the transaction leaves an empty $0 report behind in Onyx (REPORT, REPORT_ACTIONS, parent REPORT_ACTIONS preview, and SNAPSHOT) and on the server.
  3. Furthermore, getChangeTransactionsReportOnyxData never pushes searchUpdate.failureData (at src/libs/actions/Transaction.ts:1831-1836), so Search snapshot rows remain out of sync when a move fails.

What is the root cause of that problem?

  1. failureData in getChangeTransactionsReportOnyxData (src/libs/actions/Transaction.ts:1212-1224) does not set errors or errorFields on the transaction, and omits searchUpdate.failureData:
    • At src/libs/actions/Transaction.ts#L1212-L1224, failureData restores reportID: transaction.reportID, comment: transaction.comment, etc., without setting errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage') (unlike autoReportTransactions at lines 2287-2291 which explicitly sets errors on each transaction in failureData).
    • In addition, at src/libs/actions/Transaction.ts#L1831-L1836, searchUpdate.optimisticData and searchUpdate.successData are appended, but searchUpdate.failureData is never pushed to failureData.
  2. createReportForPolicy creates the report via a separate CREATE_APP_REPORT write (src/libs/actions/Report/index.ts:5131), and ChangeTransactionsReport only rolls back total / transactionCount to 0 instead of removing the newly created report:
    • In src/pages/iou/request/step/IOURequestStepReport/hooks/useReportPickerActions.ts#L226-L238 (and SearchTransactionsChangeReport.tsx), createNewReport(...) writes:
      • ${ONYXKEYS.COLLECTION.REPORT}${reportID}
      • ${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}
      • ${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}
      • ${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID} ([reportPreviewReportActionID]: optimisticReportPreview)
      • ${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}
    • Then changeTransactionsReport is queued as a second request. When changeTransactionsReport fails (e.g. 456 because the expense creation was dropped, or a server/network error), Transaction.ts:1871-1917 and 2128-2135 merge {total: 0, transactionCount: 0, nextStep: ...} into ${ONYXKEYS.COLLECTION.REPORT}${reportID}. Even if a SET: null were pushed earlier in failureData, those later Onyx.METHOD.MERGE entries in steps 8 and 9 of getChangeTransactionsReportOnyxData would re-create a partial report object in Onyx unless reportID is excluded from steps 8 & 9 when removing the newly created report!

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

  1. Set errors on the transaction in failureData (and clear errors: null in optimisticData / successData) and include searchUpdate.failureData:

    • In src/libs/actions/Transaction.ts:
      • At lines 1188-1201 (optimisticData), include errors: null on ${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}.
      • At lines 1212-1224 (failureData), add errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage'):
        failureData.push({
            onyxMethod: Onyx.METHOD.MERGE,
            key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
            value: {
                reportID: transaction.reportID,
                comment: transaction.comment,
                originalAmount: transaction.originalAmount,
                originalCurrency: transaction.originalCurrency,
                ...(shouldClearAmount && {pendingAction: transaction.pendingAction ?? null}),
                ...(shouldClearAmount && {convertedAmount: transaction.convertedAmount}),
                ...(shouldClearAmount && {convertedTaxAmount: transaction.convertedTaxAmount}),
                errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage'),
            },
        });
        
      • At lines 1831-1836, also push searchUpdate.failureData:
        if (searchUpdate?.failureData) {
            failureData.push(...searchUpdate.failureData);
        }
        
  2. Remove the newly created empty report on move failure without re-merging it in steps 8 & 9:

    • Pass isNewReport?: boolean (or reportPreviewReportActionID?: string returned by createNewReport, which already returns {...optimisticReportData, reportPreviewReportActionID} at src/libs/actions/Report/index.ts:5150) from createReportForPolicy in useReportPickerActions.ts (and SearchTransactionsChangeReport.tsx) into handleRegularReportSelection $\rightarrow$ changeTransactionsReport (ChangeTransactionsReportProps).
    • In getChangeTransactionsReportOnyxData (src/libs/actions/Transaction.ts):
      • When isNewReport && newReport?.reportID, in failureData:
        • Skip newReport.reportID in the failureData loops of Step 8 (updatedReportTotals, updatedReportUnheldTotals, updatedReportTransactionCounts, updatedReportNonReimbursableTotals, updatedReportStateNums, updatedReportReimbursableTotals) and Step 9 (affectedReportIDs) so later Onyx.METHOD.MERGE updates do not resurrect a partial report entry after SET: null.
        • Push cleanup updates to failureData to remove the empty report, its actions, its loading state, its parent chat REPORT_PREVIEW action, and its Search snapshot entry:
          const previewActionID = newReport.reportPreviewReportActionID ?? newReport.parentReportActionID;
          failureData.push(
              {
                  onyxMethod: Onyx.METHOD.SET,
                  key: `${ONYXKEYS.COLLECTION.REPORT}${newReport.reportID}`,
                  value: null,
              },
              {
                  onyxMethod: Onyx.METHOD.SET,
                  key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${newReport.reportID}`,
                  value: null,
              },
              {
                  onyxMethod: Onyx.METHOD.SET,
                  key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${newReport.reportID}`,
                  value: null,
              },
              {
                  onyxMethod: Onyx.METHOD.SET,
                  key: `${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${newReport.reportID}`,
                  value: null,
              },
          );
          if (newReport.parentReportID && previewActionID) {
              failureData.push({
                  onyxMethod: Onyx.METHOD.MERGE,
                  key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${newReport.parentReportID}`,
                  value: {
                      [previewActionID]: null,
                  },
              });
          }
          
    • Add unit tests in tests/unit/TransactionTest.ts verifying that when changeTransactionsReport fails:
      1. The transaction is restored to its original report with errors populated.
      2. When moving to a newly created report (isNewReport: true), ${ONYXKEYS.COLLECTION.REPORT}${newReport.reportID} is completely removed (null in Onyx, not left behind as a partial or $0 report) and its parent REPORT_PREVIEW action is cleaned up.

What alternative solutions did you explore? (Optional)

  • Appending SET: null for ${ONYXKEYS.COLLECTION.REPORT}${reportID} at the start of getChangeTransactionsReportOnyxData without excluding reportID from steps 8 and 9: rejected because steps 8 and 9 (lines 1881-2135) push subsequent Onyx.METHOD.MERGE updates for reportID into failureData, which would execute after the SET: null and leave a broken partial report object {total: 0, transactionCount: 0, nextStep: ...} in Onyx.

cocvn157 avatar Nov 16 '26 06:11 cocvn157

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

Proposal

Problem

When moving expenses to another report fails, the move is undone silently - the expenses reappear in the old report with no error - and if the move created a new destination report, that report is left behind, empty, with a $0 total.

Root cause

Both defects are in the failure data of changeTransactionsReport (src/libs/actions/Transaction.ts):

  1. No error is set. The transaction failure entry (lines 1214-1225) restores reportID, comment, originalAmount and originalCurrency, but contains no errors field. The user sees the expense back where it started and is told nothing.

  2. A destination report created by this flow is never cleaned up. The same function already knows how to do this: its selfDM branch appends failure entries that remove the report it created - Onyx.METHOD.MERGE with value: null for the REPORT, REPORT_METADATA and REPORT_ACTIONS keys (lines 1038-1055). The newReport branch has no equivalent, so a failed "move to new report" leaves the empty report behind.

    The flow can tell whether it created the destination: callers pass newReport as either an existing report (DynamicIOURequestEditReport.tsx) or a freshly created optimistic one (SearchTransactionsChangeReport.tsx passes optimisticReport). A just-created report carries the marker pendingFields.createReport (set at creation, src/libs/ReportUtils.ts:8570); an existing report does not.

The report totals/counts rollback already exists (lines 1870-1916) - only the error surface and the created-report cleanup are missing.

Changes

  1. Set an error on every moved transaction. Add errors to the transaction failure entry, using the generic failure pattern this file already uses for the same purpose (Transaction.ts:2290 sets errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage')). The expense returns to its original report WITH the failure shown, so the user knows the move did not happen and can retry.

  2. Delete a destination report this flow created. When newReport?.pendingFields?.createReport is set, append failure entries mirroring the selfDM cleanup in the same function - Onyx.METHOD.MERGE with value: null for:

    • ${ONYXKEYS.COLLECTION.REPORT}${newReport.reportID}
    • ${ONYXKEYS.COLLECTION.REPORT_METADATA}${newReport.reportID}
    • ${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${newReport.reportID}

    METHOD.MERGE with null, not METHOD.SET: MERGE-with-null is the pattern this codebase uses to remove a created report's keys (the selfDM branch directly above), and it does not clobber sibling state the way a SET of the whole key would. When newReport is a pre-existing report (no createReport pending field), nothing is deleted - the destination report stays, exactly as today.

Not changed: the optimistic move, the success data, the totals/counts rollback, the selfDM branch, and moves to pre-existing reports (other than now showing the error).

Tests

In tests/unit/TransactionTest.ts and tests/actions/TransactionTest.ts (both already cover changeTransactionsReport):

  • A failed move sets errors on each moved transaction and restores its original reportID.
  • A failed move to a NEW report (created by the flow) removes the destination report, its metadata and its report actions - no empty $0 report remains.
  • A failed move to a PRE-EXISTING report leaves that report in place (regression control for the createReport marker check).
  • A successful move to a new report keeps the report and clears the pending state as today.

Alternatives considered

  • METHOD.SET with null for the report cleanup (as in one existing proposal). Rejected: it contradicts the cleanup pattern used in this very function for the selfDM report; consistency here is not cosmetic, SET and MERGE behave differently for keys other writers have touched.
  • A new isNewReport parameter threaded from the callers. Rejected as unnecessary: pendingFields.createReport already records exactly this fact on the report object the function receives, and threading a param means touching all six call sites for information that is already there.
  • Delete empty $0 reports lazily on next app load. Rejected: the empty report is visible in the meantime, and a lazy sweep races with a user retrying the move into the same report.

dankezo avatar Nov 16 '26 06:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 06:11 melvin-bot[bot]

Proposal

(Latest version, updated Nov 16)

What is the root cause of that problem?

When a move fails, src/libs/actions/Transaction.ts undoes it but does two things wrong.

  1. No error is shown. The undo step for each expense (~L1215) puts the old reportID, comment and amounts back, but sets no errors. Other mutations in the same file do (autoReportTransactions uses iou.error.genericEditFailureMessage). So the expense just goes back, silently.

  2. The new report is not removed. "Create report" sends two separate requests: createNewReport (creates the report), then changeTransactionsReport (moves the expense). If the second fails, the first has already worked. The undo step only resets the new report's totals to zero, so an empty $0 report stays. The self DM report is already removed in this situation (~L1038-1055); the new destination report is not.

The code can tell the report is new: the report object from createNewReport has pendingFields.createReport (ReportUtils.ts ~L8570); an existing report does not. One trap: the undo entries for totals and counts are merges on the same report key, so they must skip the new report, or they would bring back a half-empty report after it is removed.

Search correction. I earlier said getSearchOnyxUpdate has failure data that is never used. That was wrong: it returns only optimisticData and successData (IOU/SearchUpdate.ts). So a failed move does not roll Search back, and when an expense-report or chat Search is open, createNewReport adds the new report to its snapshot with no removal on failure.

I have no production logs, so I can't say why the server rejects the move; the fix does not depend on it.

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

  1. Show an error. On failure set errors on each moving expense, and clear it in the optimistic and success data so a retry starts clean. Use the existing iou.error.genericEditFailureMessage; if reviewers want move-specific wording, I will add a key in en.ts / es.ts.
  2. Remove the report this move created, and only that one. When newReport?.pendingFields?.createReport is set, skip that report in the totals/counts undo entries, and remove the report, its actions, metadata, loading state and its preview in the parent chat (same pattern as the self DM case). The "all matching" (jsonQuery) branch gets the same. An existing report is never touched, even if it was empty. I will check that every caller passes the object from createNewReport: useReportPickerActions, SearchTransactionsChangeReport, DynamicIOURequestEditReport, DynamicIOURequestStepUpgrade, DynamicNewReportWorkspaceSelectionPage.
  3. Search. In the same failure data, remove the new report's entry from the current Search snapshot. For the moved expenses' rows, I would add failure data to getSearchOnyxUpdate that undoes its optimistic changes; if reviewers think that is too wide for this issue, it can be a follow-up.
  4. Two edge cases. If a second move into the same new report is queued before the first fails, I will check the queue order and skip removal while another pending move targets it. If the user is viewing the new report when it is removed, I will check they land on a valid page, not "not found".
  5. Server copy. Steps 1-4 are the complete App-side fix. The report also exists on the server, so local removal hides it until the next sync. I found no safe App-side delete: failure data is declarative, and deleteAppReport has its own failure data that would restore the report if that delete failed too. Either the backend deletes a report created in the same flow when the move fails, or this is handled separately. I would like an engineer's call.

Tests (tests/unit/TransactionTest.ts), with the request failing: an existing report is untouched and the expense returns with an error; with a new report, nothing is left under its key, and its actions, loading state, preview and Search entry are gone (also for jsonQuery); a retry clears the error; success is unchanged.

Demo. With the PR I will attach web and native recordings of a forced failure: before (expense jumps back, empty $0 report stays) and after (error shown, no empty report, still gone after reload).

Compared with the other proposals: jsonQuery branch, caller audit, the two edge cases, the Search correction and the server note are included here. My 08:06Z comment already had the totals-skip and preview removal, before dankezo's 11:05Z supplement.

What alternative solutions did you explore? (Optional)

  • Deleting every empty report on failure: rejected, an existing report may have been empty.
  • Only adding the error: leaves the empty $0 report.
  • Removing the report but keeping the totals undo entries: rejected, they recreate a partial report.
  • An isNewReport parameter from callers: not needed, the createReport marker already says it.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~016176d06dd16a08b7

AvikaM3192730 avatar Nov 16 '26 08:11 AvikaM3192730

📣 @AvikaM3192730! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 16 '26 08:11 melvin-bot[bot]

Proposal updated: please review this version of my proposal above (https://github.com/Expensify/App/issues/106962#issuecomment-6909629717), reformatted into the official template. The solution and scope are unchanged.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

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

When moving expenses to another report fails, the move is undone silently - the expenses reappear in the old report with no error - and if the move created a new destination report, that report is left behind, empty, with a $0 total.

What is the root cause of that problem?

Both defects are in the failure data of changeTransactionsReport (src/libs/actions/Transaction.ts):

  1. No error is set. The transaction failure entry (lines 1214-1225) restores reportID, comment, originalAmount and originalCurrency, but contains no errors field. The user sees the expense back where it started and is told nothing.

  2. A destination report created by this flow is never cleaned up. The same function already knows how to do this: its selfDM branch appends failure entries that remove the report it created - Onyx.METHOD.MERGE with value: null for the REPORT, REPORT_METADATA and REPORT_ACTIONS keys (lines 1038-1055). The newReport branch has no equivalent, so a failed "move to new report" leaves the empty report behind.

    The flow can tell whether it created the destination: callers pass newReport as either an existing report (DynamicIOURequestEditReport.tsx) or a freshly created optimistic one (SearchTransactionsChangeReport.tsx passes optimisticReport). A just-created report carries the marker pendingFields.createReport (set at creation, src/libs/ReportUtils.ts:8570); an existing report does not.

The report totals/counts rollback already exists (lines 1870-1916) - only the error surface and the created-report cleanup are missing.

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

  1. Set an error on every moved transaction. Add errors to the transaction failure entry, using the generic failure pattern this file already uses for the same purpose (Transaction.ts:2290 sets errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage')). The expense returns to its original report WITH the failure shown, so the user knows the move did not happen and can retry.

  2. Delete a destination report this flow created. When newReport?.pendingFields?.createReport is set, append failure entries mirroring the selfDM cleanup in the same function - Onyx.METHOD.MERGE with value: null for:

    • ${ONYXKEYS.COLLECTION.REPORT}${newReport.reportID}
    • ${ONYXKEYS.COLLECTION.REPORT_METADATA}${newReport.reportID}
    • ${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${newReport.reportID}

    METHOD.MERGE with null, not METHOD.SET: MERGE-with-null is the pattern this codebase uses to remove a created report's keys (the selfDM branch directly above), and it does not clobber sibling state the way a SET of the whole key would. When newReport is a pre-existing report (no createReport pending field), nothing is deleted - the destination report stays, exactly as today.

Not changed: the optimistic move, the success data, the totals/counts rollback, the selfDM branch, and moves to pre-existing reports (other than now showing the error).

Tests:

In tests/unit/TransactionTest.ts and tests/actions/TransactionTest.ts (both already cover changeTransactionsReport):

  • A failed move sets errors on each moved transaction and restores its original reportID.
  • A failed move to a NEW report (created by the flow) removes the destination report, its metadata and its report actions - no empty $0 report remains.
  • A failed move to a PRE-EXISTING report leaves that report in place (regression control for the createReport marker check).
  • A successful move to a new report keeps the report and clears the pending state as today.

What alternative solutions did you explore? (Optional)

  • METHOD.SET with null for the report cleanup (as in one existing proposal). Rejected: it contradicts the cleanup pattern used in this very function for the selfDM report; consistency here is not cosmetic, SET and MERGE behave differently for keys other writers have touched.
  • A new isNewReport parameter threaded from the callers. Rejected as unnecessary: pendingFields.createReport already records exactly this fact on the report object the function receives, and threading a param means touching all six call sites for information that is already there.
  • Delete empty $0 reports lazily on next app load. Rejected: the empty report is visible in the meantime, and a lazy sweep races with a user retrying the move into the same report.

dankezo avatar Nov 16 '26 10:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 10:11 melvin-bot[bot]

Proposal supplement: three additions to my proposal above (https://github.com/Expensify/App/issues/106962#issuecomment-6913476626), from re-checking the failure path in getChangeTransactionsReportOnyxData end to end. The two fixes already proposed (set errors on the moved transactions, delete a destination report this flow created) stand; the additions below are needed for the second one to actually hold.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

What the additions change

  1. Exclude the created report from the step 8 and 9 rollback entries. The totals/counts rollback (steps 8 and 9 of getChangeTransactionsReportOnyxData, from src/libs/actions/Transaction.ts:1870 on) pushes Onyx.METHOD.MERGE failure entries for the destination report - total, unheldTotal, transactionCount and the other totals - and those entries sit AFTER the transaction failure entries in the same failureData array. So a cleanup entry for a just-created report, appended where I originally proposed it, would be followed by MERGE entries that re-create the report key as a partial object ({total: 0, transactionCount: 0, ...}) - the empty $0 report would still be there, just thinner. When the destination report carries pendingFields.createReport, it must also be left out of the step 8 and 9 failure loops for that report (the loops already skip reports in skippedReportIDsSet), so the deletion is the last word on that key.

  2. Append searchUpdate.failureData. At src/libs/actions/Transaction.ts:1831-1836, searchUpdate.optimisticData and searchUpdate.successData are appended to the onyx data, but searchUpdate.failureData never is. On a failed move, Search snapshot rows therefore stay in the moved state even though the transactions themselves roll back. Add the missing push next to the other two: if (searchUpdate?.failureData) { failureData.push(...searchUpdate.failureData); }.

  3. Remove the parent chat's report preview for the created report. The cleanup in my proposal removes the created report's REPORT, REPORT_METADATA and REPORT_ACTIONS keys. createNewReport also wrote an optimistic report-preview action into the parent chat's REPORT_ACTIONS (its return value carries reportPreviewReportActionID). If only the report's own keys are removed, that preview action is left pointing at a report that no longer exists. The failure data should also MERGE {[reportPreviewReportActionID]: null} into the parent report's REPORT_ACTIONS key, and clear the created report's RAM_ONLY_REPORT_LOADING_STATE entry.

Tests added to the ones already proposed:

  • A failed move to a NEW report leaves NO entry at all under the destination's REPORT key afterwards (not a partial totals object) - this is the step 8 and 9 exclusion working.
  • A failed move restores the Search snapshot rows for the moved transactions (the searchUpdate.failureData push).
  • After a failed move to a new report, the parent chat no longer holds a report-preview action for the deleted report.

Nothing else in the proposal changes: the errors surface, the pendingFields.createReport marker (no new parameter), and the MERGE-with-null cleanup pattern mirroring the selfDM branch all stay as proposed above.

dankezo avatar Nov 16 '26 11:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 11:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~014898525b9c53fc32

Proposal

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

When moving an expense to another report fails on the backend, the moved expense reverts back to its original report silently without presenting any user error or notification, while an orphaned, empty $0 destination report stays behind in the user's report list.

What is the root cause of that problem?

In src/libs/actions/Transaction.ts (specifically in changeTransactionsReport and getChangeTransactionsReportOnyxData):

  1. When moving expenses to a new report (props.newReport), optimisticData creates and adds the destination report into Onyx.
  2. When the backend request fails, failureData in changeTransactionsReport (lines 2183-2187) only merges:
    value: {pendingFields: {reportID: null}}
    
    It never clears or nullifies the newly created optimistic destination report (props.newReport.reportID). Because the expense rolled back to the old report, the destination report remains in Onyx with total = $0 and 0 transactions.
  3. Furthermore, neither sourceReport nor the moved transaction records any error in errorFields or dispatches an error alert to inform the user that the move was rejected. The failure occurs completely silently.

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

  1. In src/libs/actions/Transaction.ts: In failureData of changeTransactionsReport and getChangeTransactionsReportOnyxData:
    • If a new destination report was optimistically created for the move (props.newReport or isNewReport), add an Onyx SET or nullification in failureData to remove the empty orphan report:
      if (isNewDestinationReport && props.newReport) {
          failureData.push({
              onyxMethod: Onyx.METHOD.SET,
              key: `${ONYXKEYS.COLLECTION.REPORT}${props.newReport.reportID}`,
              value: null,
          });
      }
      
    • On the source report / original transaction, record an error in errorFields so an actionable error notice / banner appears informing the user that the transaction could not be moved:
      failureData.push({
          onyxMethod: Onyx.METHOD.MERGE,
          key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`,
          value: {
              errorFields: {
                  reportID: ErrorUtils.getMicroSecond(),
              },
          },
      });
      
  2. In src/libs/ErrorUtils.ts (or report error translation): Map the move failure error key to display: "Unable to move expense. Please try again."

What alternative solutions did you consider?

  • Leaving the empty destination report open with an error banner: Rejected because an empty $0 report with no expenses clutters the report list and violates the clean rollback principle.
  • Only showing a Growl/Toast notification: Rejected because toast notifications can be missed if the user switches tabs, whereas setting errorFields keeps the red brick road visible on the expense.

RajGahoi avatar Nov 16 '26 12:11 RajGahoi

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 12:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~016176d06dd16a08b7

AvikaM3192730 avatar Nov 16 '26 13:11 AvikaM3192730

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 13:11 melvin-bot[bot]

Proposal

Updated Corrected the server-copy step; latest version is in my original comment above.

AvikaM3192730 avatar Nov 16 '26 13:11 AvikaM3192730

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 13:11 melvin-bot[bot]

Proposal

Updated Consolidated and corrected the Search handling; latest version is in my original comment above.

AvikaM3192730 avatar Nov 16 '26 13:11 AvikaM3192730