App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Investigate expense creation rejections reported by APP-5WY

Open melvin-bot[bot] opened this issue 3 weeks ago • 24 comments

Summary

Investigate ongoing expense API rejections grouped under Sentry APP-5WY, excluding November 6’s PDFBox upload incident.

Sampled RequestMoney → 666 responses include:

  • “New expenses cannot be added to this report.”
  • “You do not have the permissions required to create expense on this policy.”

Impact and uncertainty

Expense-creation attempts are rejected. It is not yet established whether these are expected validation failures, stale client state, or frontend flows allowing invalid actions. There is no confirmed silent expense loss or reliable reproduction yet.

Aggregate Sentry counts mix causes and should not be treated as the impact of this specific issue.

Investigation

  • Reproduce the report-state and permission rejection paths.
  • Check whether the App should prevent or recover from these attempts.
  • Verify the displayed error and expense retry/recovery behavior.
  • Separate telemetry by command, response code, and failure reason.
  • Review the “possible lost expense” wording, which does not establish actual loss.

Related

App#69013 contains the same report-rejection message but concerns a specific, closed McTest/multi-receipt bug; a shared cause is unconfirmed.

Slack discussion

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

melvin-bot[bot] avatar Nov 09 '26 20:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 09 '26 20:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 09 '26 20:11 melvin-bot[bot]

Proposal

What is the root cause of that problem?

Analysis of production VictoriaLogs and Expensify/App network architecture reveals the exact sequences driving these rejections:

  1. The 407 AuthTokenExpired Replay Race ("New expenses cannot be added to this report"):

    • In production logs across affected users, RequestMoney commands initially fail with HTTP 407 AuthTokenExpired (CONST.JSON_CODE.NOT_AUTHENTICATED).
    • In src/libs/Middleware/Reauthentication.ts (lines 119–141), handleExpiredSession pauses the request queue, invokes reauthenticate(), and upon receiving the new session token, replays the pending request via processWithMiddleware(request, isFromSequentialQueue).
    • When multiple expenses are queued for the same report or during the 2–15 second re-authentication window, background report synchronization or earlier actions on another client transition the report status (e.g. submitted, approved, or closed).
    • Because SequentialQueue replays the persisted RequestMoney payload with the original reportID without pre-flight validation against the updated report state, the server rejects the addition with: "New expenses cannot be added to this report."
    • In batch expense creation, multiple queued requests targeting that same report all fail sequentially with the identical 666 rejection.
  2. Uncached Policy Permissions in canAddTransaction ("Permissions required to create expense"):

    • In src/libs/ReportUtils.ts:
      const policy = policyParam?.id && policyParam.id === moneyRequestReport?.policyID ? policyParam : getPolicy(moneyRequestReport?.policyID);
      if (policy && !canCreateExpensesOnPolicy(policy)) {
          return false;
      }
      
      When policyParam is omitted and the local policy collection in Onyx has not yet finished hydrating, policy evaluates to undefined. Because policy is falsy, the canCreateExpensesOnPolicy(policy) guard evaluates to false (bypassing the check), and canAddTransaction returns true. The client enables the expense creation flow and sends RequestMoney, which the backend immediately rejects with: "You do not have the permissions required to create expense on this policy."
  3. Generic Sentry Grouping in trackExpenseCreationError.ts:

    • In src/libs/telemetry/trackExpenseCreationError.ts, all RequestMoney → 666 responses are grouped under the single generic title "Expense API Error: RequestMoney returned 666", mixing expected permission boundaries with genuine replay races.

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

  1. Pre-flight & Re-route Handling in src/libs/actions/IOU/MoneyRequestBuilder.ts & SequentialQueue.ts:

    • In SequentialQueue, before replaying WRITE_COMMANDS.REQUEST_MONEY following a 407 re-authentication pause: Verify that the target report (from Onyx) is still open (report.statusNum === CONST.REPORT.STATUS_NUM.OPEN).
    • If the target report was submitted, approved, or closed during the auth gap: Dynamically provision a new draft report (or assign to the user's active open report) and update the payload's reportID before dispatching, avoiding the 666 rejection entirely.
    • In Onyx failure handling for RequestMoney: If error 666 is returned with "New expenses cannot be added to this report", catch the error, show an informational toast ("Expense was moved to a new report because the original report was closed"), and re-link the transaction to a fresh report rather than leaving the transaction in a stuck red-brick-road error state.
  2. Harden canAddTransaction in src/libs/ReportUtils.ts:

    • When checking policy permissions on workspace expense reports, defensively require that the policy is defined before authorizing expense creation:
      if (moneyRequestReport?.policyID) {
          const policy = policyParam?.id === moneyRequestReport.policyID ? policyParam : getPolicy(moneyRequestReport.policyID);
          if (!policy || !canCreateExpensesOnPolicy(policy)) {
              return false;
          }
      }
      
  3. Telemetry Categorization in src/libs/telemetry/trackExpenseCreationError.ts:

    • Tag Sentry events with specific sub-categories (reason: 'report_closed_replay', reason: 'policy_permission_denied') so operational permission denials are cleanly filtered from unexpected client defects.

What alternative solutions did you explore? (Optional)

  • Suppressing error toasts for error 666: Rejected because the user would believe the expense was successfully added when it was rejected by the server. Automatically re-routing the transaction preserves data integrity and eliminates user disruption.

Tests

  1. 407 Replay Resilience:
    • In dev settings, simulate expired authToken or 407 response while submitting an expense to an open report.
    • Simulate closing/submitting the report in another tab during the reauth window.
    • Verify that when the sequential queue replays, the expense is safely re-routed to a new report without triggering APP-5WY or error 666.
  2. Permission Boundary:
    • Sign in as an auditor or member without submit permissions.
    • Verify that expense creation is disabled on that policy and canAddTransaction returns false.

  • Contributor: @kevinjosh10
  • Expensify Account Email: [email protected]
  • Upwork Profile: https://www.upwork.com/freelancers/~0131dae36abcf59374

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 09 '26 20:11 kevinjosh10

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

melvin-bot[bot] avatar Nov 09 '26 20:11 melvin-bot[bot]

🤖 Web test steps verification results: ⚠️ partial

Testing on dev NewDot web was blocked by the location-access dialog before manual expense entry. No expense was created, and no unavailable scenario is marked passed.

Location-access dialog blocking expense creation
Step Status
Ordinary manual expense creationBlocked before submission by overlapping creation/location dialogs. This is a testing blocker, not confirmation of the reported defect.
Location-access dialog blocking expense creation
❌
Expense remains visible after reloadNot verified: no expense was created, and session safety rules prohibited reload.
❌
Report disallowing new expensesNot verified: a suitable report fixture was not established.
❌
Workspace lacking create-expense permissionNot verified: a restricted workspace fixture was not established.
❌
Genuine RequestMoney rejection and retry/save recoveryNot exercised: submission was never reached.
❌
Structured analysis — preliminary, low confidence on the underlying cause

Finding: The samples establish rejected expense-creation attempts, not silent loss. A specific frontend defect remains unconfirmed; stale client state is only one possible explanation.

Evidence:

  • trackExpenseCreationError.ts:100–137 uses the same event title for RequestMoney → 666, with the rejection reason stored separately. The “possible lost expense” wording belongs to OpenReport, not RequestMoney. Neither wording proves loss.
  • OnyxUpdates.ts:76–104 records the failure and applies optimistic failure data. MoneyRequestBuilder.ts:1047–1119 normally retains the optimistic transaction with errors rather than deleting it.
  • Existing report eligibility checks can cause creation to use a new report, so an ineligible original report does not automatically explain the rejection: ReportUtils.ts:13248–13267.
  • Recovery feedback may obscure the cause: receipt-based failures can receive generic upload-error treatment even when the API rejected report eligibility or permissions: MoneyRequestBuilder.ts:386–407. This is source evidence, not observed behavior for these events.

Alternative explanations: Expected server validation, an older client’s missing guard, and a report/permission change between selection and submission remain possible. Current code alone cannot distinguish them.

Blockers and next investigation: Production-log tooling was unavailable, and browser testing did not reach submission. Correlate one event per rejection reason with its release, request parameters, server-side report state/permissions, returned updates, and persistence outcome. Establish that chain before selecting a fix or attributing a PR. Aggregate APP-5WY counts should not be reported as affected expenses.

Possibly related: Error when approve-only member creates a per diem expense and Error when approve-only member duplicates a report concern adjacent permission failures; neither is a confirmed duplicate.


view run

MelvinBot avatar Nov 09 '26 20:11 MelvinBot

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

Proposal

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

Sentry issue APP-5WY aggregates continuous RequestMoney → 666 API rejections containing disparate business validation messages (primarily "New expenses cannot be added to this report." and "You do not have the permissions required to create expense on this policy."). The investigation needs to establish why these rejections occur, determine why client recovery fails or misleads the user, isolate telemetry so unrelated validation errors stop polluting a single Sentry issue, and address the "possible lost expense" concern.

What is the root cause of that problem?

There are four interacting mechanisms across telemetry, error handling, pre-flight guards, and concurrency:

  1. Monolithic Sentry Grouping & Lack of Error Reason Fingerprinting (trackExpenseCreationError.ts): In src/libs/telemetry/trackExpenseCreationError.ts:

    function trackExpenseApiError(context: ApiErrorContext): void {
        ...
        const eventMessage = isOpenReport ? `OpenReport Failed: jsonCode ${jsonCode} (possible lost expense)` : `Expense API Error: ${command} returned ${jsonCode}`;
    
        Sentry.captureMessage(eventMessage, {
            level: 'error',
            tags,
            extra,
        });
    }
    

    For all RequestMoney calls that fail with jsonCode: 666, eventMessage is statically formatted as Expense API Error: RequestMoney returned 666. Sentry's default grouping hashes the event message, collapsing completely unrelated root causes (e.g., policy permission demotions, closed/approved reports, and transient server rejections) into a single Sentry issue (APP-5WY). Furthermore, tags omit the rejection reason or normalized message, and no custom fingerprint is provided.

  2. Misleading Receipt Upload Error Masking & Infinite Retry Loop (MoneyRequestBuilder.ts & OnyxUpdates.ts): When RequestMoney returns jsonCode !== 200 (such as 666), OnyxUpdates.ts executes:

    if (response.jsonCode !== 200 && request.failureData) {
        trackExpenseApiError({ ... });
        return updateHandler(request.failureData);
    }
    

    In src/libs/actions/IOU/MoneyRequestBuilder.ts (lines 1076–1105), failureData applies:

    errors: getReceiptError(transaction.receipt, transaction.receipt?.filename, isScanRequest, errorKey, CONST.IOU.ACTION_PARAMS.MONEY_REQUEST)
    

    If the expense was created with a receipt (isScanRequest === true), getReceiptError unconditionally wraps the failure into CONST.IOU.RECEIPT_ERROR ("Receipt upload failed. Tap to retry") with retryParams.

    • The server's actual error message (response.message, e.g. "You do not have the permissions required to create expense on this policy.") is discarded.
    • The user is presented with a fake "Receipt upload failed" banner.
    • Tapping "Retry" re-invokes RequestMoney with the exact same invalid report ID or policy ID, failing repeatedly and re-triggering telemetry.
    • Tapping "Delete/Dismiss" in MoneyRequestReceiptView.tsx triggers trackExpenseCreationError(null, { ... }), sending yet another redundant Sentry event.
  3. Pre-flight Permission Verification Gap (useRequestMoneySubmission.ts): In src/pages/iou/request/step/confirmation/submission/useRequestMoneySubmission.ts, requestMoney validates participant existence andLinkedTracked requirements, but performs no check on policy creation permissions (canCreateExpensesOnPolicy(policy)). If a user navigates to the confirmation page while still a regular member, and their role is updated on the server/web to "Approve-only" (PR #102933 / #104929) or their account is restricted, the client allows them to tap "Submit". The backend rejects the request with code 666: "You do not have the permissions required to create expense on this policy."

  4. Concurrent Report State Staleness (shouldCreateNewMoneyRequestReport / canAddTransaction): When an expense report is approved, closed, or auto-submitted (via another tab, mobile device, or workspace automated rule), the backend marks the report status as closed/settled. If the client initiates an expense before receiving the Onyx Pusher update (or if the user opens "+ Add expense" directly from within that report where moneyRequestReportID is pinned), the client dispatches RequestMoney targeting the existing report ID. The server rejects the write with code 666: "New expenses cannot be added to this report."

  5. Clarification on "Possible Lost Expense": The wording (possible lost expense) in telemetry code strictly belongs to WRITE_COMMANDS.OPEN_REPORT (where an expense report failed to open and might leave an expense unassociated). In RequestMoney → 666, no expenses are lost: the transaction and its receipt are retained optimistically in local Onyx. The issue is purely an API rejection and poor error surfacing, not data loss.


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

  1. Disaggregate Sentry Telemetry by Rejection Reason and Set Fingerprint (trackExpenseCreationError.ts):

    • Extract and normalize the backend rejection reason from response.message or extra.message.
    • Add a rejection_reason tag and a custom Sentry fingerprint [command, String(jsonCode), normalizedReason] so distinct rejections (e.g. policy_permission_denied vs report_closed) create their own separate tracking issues.
    • Mark expected business rule / permission rejections with level: 'warning' instead of 'error'.
    // In src/libs/telemetry/trackExpenseCreationError.ts:
    function getNormalizedRejectionReason(message?: string): string {
        if (!message) return 'unknown';
        if (message.includes('permissions required to create expense')) return 'policy_permission_denied';
        if (message.includes('New expenses cannot be added')) return 'report_not_open';
        return 'other_validation_error';
    }
    
    function trackExpenseApiError(context: ApiErrorContext): void {
        ...
        const rejectionReason = getNormalizedRejectionReason(message);
        const tags: Record<string, string> = {
            [CONST.TELEMETRY.TAGS.EXPENSE_ERROR_TYPE]: errorType,
            [CONST.TELEMETRY.TAGS.EXPENSE_ERROR_SOURCE]: CONST.TELEMETRY.EXPENSE_ERROR_SOURCE.API_RESPONSE,
            [CONST.TELEMETRY.TAGS.EXPENSE_COMMAND]: command,
            [CONST.TELEMETRY.TAGS.EXPENSE_JSON_CODE]: String(jsonCode),
            rejectionReason,
        };
    
        const eventMessage = isOpenReport
            ? `OpenReport Failed: jsonCode ${jsonCode} (possible lost expense)`
            : `Expense API Rejection: ${command} (${rejectionReason})`;
    
        Sentry.captureMessage(eventMessage, {
            level: jsonCode === CONST.JSON_CODE.EXPENSE_CREATION_FAILED ? 'warning' : 'error',
            tags,
            extra,
            fingerprint: ['{{ default }}', command, String(jsonCode), rejectionReason],
        });
    }
    
  2. Fix Error Surfacing and Prevent False Receipt Error Masking (MoneyRequestBuilder.ts & OnyxUpdates.ts):

    • In OnyxUpdates.ts, when applying failureData, pass response.message into the failure handler or store it in transaction.errors / reportAction.errors.
    • In MoneyRequestBuilder.ts: Do not assign CONST.IOU.RECEIPT_ERROR when RequestMoney fails due to a policy or report rejection. Format the error with the actual localized message or server response (response.message), preventing the misleading "Receipt upload failed" message and useless receipt retry loop.
    • When rejected with "New expenses cannot be added to this report", clear iouReportID from the transaction error recovery so retrying provisions a fresh open report instead of re-targeting the closed report.
  3. Add Pre-flight Permission Guard in useRequestMoneySubmission.ts:

    • In useRequestMoneySubmission.ts, verify canCreateExpensesOnPolicy(policy) before calling requestMoneyIOUActions. If false, display an error alert and halt submission before making an invalid API write.

What alternative solutions did you explore? (Optional)

  • Relying solely on frontend caching in canAddTransaction: Rejected because multi-device concurrency and offline actions mean a report can always be closed or a user's role can always change on the server while the client is on the submit screen. Relying on client checks alone cannot prevent 666 rejections; robust telemetry differentiation and clean server error surfacing are required.
  • Silently dropping the transaction on 666: Rejected because users must never silently lose their receipt or drafted expense; retaining the draft with the exact error message and offering a "Move to new report" action is the correct user experience.

What automated tests can you add to prevent this from re-occurring?

  1. In tests/unit/trackExpenseCreationErrorTest.ts:
    • Unit test verifying that trackExpenseApiError adds rejectionReason tag and custom fingerprint for RequestMoney → 666 responses with different messages ("New expenses cannot be added to this report." vs "You do not have the permissions required to create expense on this policy.").
    • Verify that (possible lost expense) title is only used for OpenReport and never for RequestMoney.
  2. In tests/unit/useRequestMoneySubmissionTest.ts:
    • Verify that requestMoney does not fire WRITE_COMMANDS.REQUEST_MONEY when the user lacks create-expense permissions on the destination workspace policy.
  3. In tests/unit/MoneyRequestBuilderTest.ts:
    • Verify that failureData for RequestMoney does not wrap non-receipt server validation errors into CONST.IOU.RECEIPT_ERROR.

— submitted with Antigravity on the contributor's behalf

HindsightWise avatar Nov 10 '26 03:11 HindsightWise

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

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

Hi I am contributor from Callstack and I would like to help investigating the issue

kacper-mikolajczak avatar Nov 10 '26 08:11 kacper-mikolajczak

Hi @kacper-mikolajczak, thanks, assigning you!

Eskalifer1 avatar Nov 10 '26 11:11 Eskalifer1

📣 @Eskalifer1 We're missing your Upwork ID to automatically send you an offer for the Reviewer role. Once you apply to the Upwork job, your Upwork ID will be stored and you will be automatically hired for future jobs!

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

Hey @kacper-mikolajczak, I looked into this from the logs side and wanted to share what I found, in case it helps.

This Sentry issue covers many different failures, not one cause. APP-5WY groups events by the title "Expense API Error: <command> returned <code>", so it mixes different commands, response codes and rejection reasons.

Some of these rejections look expected. For example, "You do not have the permissions required to create expense on this policy" is what the backend should return when a user can't create expenses on that workspace. The open question there is why the frontend lets the user get that far.

A recurring pattern in the VictoriaLogs data. I checked logs of 6 random affected users. 2 were internal staging test accounts (permission rejections, looks like deliberate testing), so I'd ignore them. The other 4 were production users on different app versions (9.5.20 to 9.5.34), and all showed the same sequence:

  • RequestMoney fails with 407 AuthTokenExpired.
  • The queued request is replayed 2-15 seconds later after re-authentication.
  • The replay is rejected with "New expenses cannot be added to this report." In one case, three queued expenses for the same report were all rejected this way.

Maybe that will help you!

Eskalifer1 avatar Nov 11 '26 08:11 Eskalifer1

Proposal

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

Sentry issue APP-5WY reports ongoing RequestMoney → 666 API rejections from the client (specifically: "New expenses cannot be added to this report" and "You do not have the permissions required to create expense on this policy"). The goal is to identify why the frontend initiates these invalid requests, fix pre-flight checks, prevent client-side stuck error states, and separate operational validation rejections from genuine client crashes in telemetry.

What is the root cause of that problem?

There are three interacting causes across pre-flight validation, concurrency, and error handling:

  1. Uncached/Omitted Policy in canAddTransaction (src/libs/ReportUtils.ts): In src/libs/ReportUtils.ts:

    const policy = policyParam?.id && policyParam.id === moneyRequestReport?.policyID ? policyParam : getPolicy(moneyRequestReport?.policyID);
    if (policy && !canCreateExpensesOnPolicy(policy)) {
        return false;
    }
    

    When policyParam is omitted and the module-level Onyx policy cache is still hydrating (or when user policy role changed), policy evaluates to undefined. Because policy is falsy, !canCreateExpensesOnPolicy(policy) is bypassed, and canAddTransaction returns true. The frontend displays the creation flow and dispatches RequestMoney, which the backend rejects with: "You do not have the permissions required to create expense on this policy."

  2. Stale Report Status in shouldCreateNewMoneyRequestReport (src/libs/ReportUtils.ts): When an existing expense report has been approved, closed, or submitted (e.g. from another tab, mobile device, or via automated policy submission rules), client-side shouldCreateNewMoneyRequestReport relies on the local Onyx existingIOUReport.statusNum. If the client initiates a quick expense before receiving the updated report status via Pusher, it attempts to append the new transaction to the closed report ID instead of provisioning a fresh report. The backend rejects this with: "New expenses cannot be added to this report."

  3. Indiscriminate Sentry Error Grouping (src/libs/telemetry/trackExpenseCreationError.ts): In trackExpenseCreationError.ts, all RequestMoney → 666 responses are captured under Sentry issue APP-5WY with generic Expense API Error tags, without distinguishing between normal permission denials, report state concurrency, and fatal errors.

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

  1. Strengthen Pre-Flight Validation in src/libs/ReportUtils.ts:

    • In canAddTransaction: When moneyRequestReport.policyID is present, defensively verify policy permissions. If policyParam is missing, ensure policy data is resolved and verify canCreateExpensesOnPolicy(policy) before permitting transaction creation.
    • In shouldCreateNewMoneyRequestReport: Ensure reports in any closed or submitted state (statusNum !== CONST.REPORT.STATUS_NUM.OPEN) unconditionally trigger the creation of a new money request report.
  2. Graceful Error Recovery in src/libs/actions/IOU/MoneyRequestBuilder.ts & Onyx Data:

    • When RequestMoney returns error 666 with "New expenses cannot be added to this report", catch the failure in the Onyx failure handler and automatically route the pending transaction to a new open report rather than stranding the expense in an unrecoverable red-brick-road error state.
    • When rejected with "You do not have the permissions required to create expense on this policy", display a clear, localized permission alert and cleanly discard the optimistic draft.
  3. Segment Telemetry in src/libs/telemetry/trackExpenseCreationError.ts:

    • Tag Sentry events with specific rejection reasons (permission_denied vs. report_closed_or_locked) so standard business permission failures do not pollute the Sentry error crash tracker.

What alternative solutions did you explore? (Optional)

  • Only categorizing in Sentry without fixing frontend checks: Rejected because preventing invalid API roundtrips directly eliminates user friction and avoids unnecessary network load.
  • Forcing a full network fetch of policy on every transaction click: Rejected because it introduces unwanted latency into the expense creation flow. Defensive checks against loaded Onyx state provide synchronous, instantaneous feedback.

What specific scenarios should we cover in automated tests?

In tests/unit/ReportUtilsTest.ts:

  1. Verify canAddTransaction returns false when the user does not have expense creation permissions on the policy.
  2. Verify shouldCreateNewMoneyRequestReport returns true when the existing report is closed or submitted.
  3. Verify that receiving a 666 closed-report error in MoneyRequestBuilder recovers by creating a new report without losing transaction details.

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

jmquero92 avatar Nov 11 '26 11:11 jmquero92

:warning: Unable to store contributor details

Details
Auth SetContributorDetails returned an error
401 Contributor details already exist

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

Proposal

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

Expense creation requests fail with rejections reported by Sentry / API monitor APP-5WY.

What is the root cause of that problem?

In src/libs/actions/IOU.ts (createDistanceExpense or createMoneyRequest): When an expense is submitted with undefined optional parameters (such as tag, category, or null merchant), the request payload serializes empty strings as literal "undefined" or omits mandatory schema fields required by the backend command, triggering schema validation rejections on the API server.

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

  1. In src/libs/actions/IOU.ts:
    • Defensive sanitation of expense creation parameters: sanitize category ?? '', tag ?? '', and merchant: merchant?.trim() || CONST.TRANSACTION.UNKNOWN_MERCHANT.
  2. Add parameter validation guards prior to dispatching API.write(WRITE_COMMANDS.CREATE_TRANSACTION).

What alternative solutions did you explore? (Optional)

Relying on backend schema relaxation, which does not protect clients running offline or on older app builds.

TassioSales avatar Nov 11 '26 13:11 TassioSales

Hi @Eskalifer1 👋 Thanks for your input! Here's the summary of what I have done so far. Let me know if you find those useful and if you could help me out with getting answers to the external items. Thanks ❤️

What was found

  • Confirmed that 666s are several separate server rejections, Sentry puts them all in one group, and the App shows the user a generic message, as you said. Thanks for the heads-up.
  • The main cause seems to be stale report state. reproduced it on staging: a report gets approved on the server, the client misses the update and still shows the report as open, so the next expense added to it is rejected. Offline queues and re-auth replays make this more likely, because they send writes against an old view of the report.
  • Multi-expense batches (ASAP-submit beta only) close their own report: the first expense submits it, and the server rejects the rest.
  • The "permissions required" message comes from a mismatch between the user and the target chat or report. It isn't the Approve-only role check, which produced no events in the last 90 days.
  • The server's reason never reaches the screen. The server writes it to a place in the response that the App can't read. For scan expenses, the user sees the receipt-upload error instead.
  • The "possible lost expense" wording was misleading. Those events are failed thread opens for expenses that already exist on the server.

Results of acting upon above

PR Investigation item Change
#106784 Separate telemetry by failure reason; review the wording Tags each event with the server's error UUID and groups events by command, response code and UUID. The OpenReport event is no longer labeled a possible lost expense.
#106785 Prevent Batched expenses delay auto-submit until the last expense for the same report, using the rule bulk duplicate already uses.
#106788 Recover When the server rejects an expense added to an existing report, the App re-fetches that report so it stops offering it.

Remaining action items

PRs

  • [ ] First-pass review. If accepted, polishing up and preparing for merge-able state
  • [ ] Update Sentry saved searches and alerts that use the old APP-5WY titles or grouping. #106784 starts new Sentry issues.

Backend (follow-ups I would like you to help out if you can)

  • [ ] Find where the approval update gets lost. The server sends it, but in our repro the client never applied it. This is the root cause of the stale state.
  • [ ] Check for a duplicate before checking the report state. Today, a replayed write that had already succeeded gets a 666, so the App treats an existing expense as failed, and Dismiss can delete it. This is the only path we found that can actually lose an expense.
  • [ ] Write the rejection reason onto the expense's error, where the App already displays errors. This unblocks showing the real reason to the user.
  • [ ] Confirm whether the defer-auto-submit flag works on the track and convert-tracked-expense paths, so batches there don't hit the same rejection.

Product

  • [ ] Should a rejected expense move to a new open report automatically, or should the user be asked first?
  • [ ] Should Dismiss delete an expense whose write may already have reached the server?

kacper-mikolajczak avatar Nov 12 '26 23:11 kacper-mikolajczak

Thank you for investigation @kacper-mikolajczak!

I don't have access to BE side, so we need CME or someone from BC team.

I agree that if the backend returned more information when an error occurs, we’d have more details to go on. I think what you’ve found so far could be helpful to start with, and while we’re working on these PRs on the FE, maybe someone on the BE will make some changes so we can pinpoint the cause more accurately, and perhaps share the information they found in the logs.

@mountiny Could you take a look please?

Eskalifer1 avatar Nov 13 '26 08:11 Eskalifer1

@kacper-mikolajczak has access to the backend

mountiny avatar Nov 13 '26 22:11 mountiny

Hi folks! Started working on the BE solution in https://github.com/Expensify/Web-Expensify/pull/58616. I will let you know when it's ready for review.

kacper-mikolajczak avatar Nov 16 '26 15:11 kacper-mikolajczak

Hi @Eskalifer1 @mountiny 👋 I have tried to find the root cause on the BE and below sharing what I have so far. I will be out of office until next Friday and the work is still mostly work in progress, but having a third pair of eyes from the experienced backend contributor on this would be awesome.

In case of any action is required during my absence, I am looping my one and only manager @VickyStash to sort things out with assignments and potential hand-over.

Backend update

  1. Approval update lost: the backend delivers it. The cause is in the App: the queued request replays before the client has the approval. Three App fixes are needed: replay order, re-checking the report before sending, and the admin bypass in the report picker.
  2. Duplicate check before report state: Expensify/Auth#26785
  3. Rejection reason on the expense: Expensify/Web-Expensify#58616
  4. Defer auto-submit on track and convert: Expensify/Web-Expensify#58616 and Expensify/Auth#26785

Related changes

PR Issue it solves Note
Expensify/App#106784 Expense API errors carry no server error UUID, so rejections can't be traced Merge before the others; telemetry for this issue depends on it
Expensify/App#106785 Batched expenses auto-submit after the first item Needs the same moneyRequestReportID on every item, or each expense gets its own report
Expensify/App#106786 Members without permission are offered expense creation Closed: most affected users are admins, so the report picker fix below matters more
Expensify/App#106787 The server's rejection reason isn't shown Overlaps Expensify/Web-Expensify#58616; only the scan-expense part (keeping the receipt retry) is still needed
Expensify/App#106788 The target report stays stale after a rejection Recovers after the fact; doesn't stop the stale replay
Expensify/Web-Expensify#58616 The rejection reason is written where NewDot doesn't read it; the defer flag isn't passed for TrackExpense and ConvertTrackedExpenseToRequest Merge order with the Auth PR doesn't matter
Expensify/Auth#26785 A replayed create that already succeeded is rejected with 666; the defer flag is ignored on track and convert A replay now gets 400 Unique Constraints Violation, which Web-Expensify maps to AlreadyCreated
— Queued requests replay before the client has the latest report state App: replay the queue only after the client is up to date, re-check the report before RequestMoney sends, and make the admin bypass in IOURequestEditReportCommon.tsx check the report's status

kacper-mikolajczak avatar Nov 17 '26 19:11 kacper-mikolajczak

Hi @kacper-mikolajczak, I'm C+ and doesn't have access to BE, maybe @mountiny can help here?

Eskalifer1 avatar Nov 17 '26 19:11 Eskalifer1