[$175] Investigate expense creation rejections reported by APP-5WY
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.
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022119893442168109846
- Upwork Job ID: 2119893442168109846
- Last Price Increase: 2026-11-09
Issue Owner
Current Issue Owner: @ShridharGoel
Triggered auto assignment to Contributor-plus team member for initial proposal review - @Eskalifer1 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022119893442168109846
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:
-
The 407 AuthTokenExpired Replay Race ("New expenses cannot be added to this report"):
- In production logs across affected users,
RequestMoneycommands initially fail with HTTP 407AuthTokenExpired(CONST.JSON_CODE.NOT_AUTHENTICATED). - In
src/libs/Middleware/Reauthentication.ts(lines 119–141),handleExpiredSessionpauses the request queue, invokesreauthenticate(), and upon receiving the new session token, replays the pending request viaprocessWithMiddleware(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
SequentialQueuereplays the persistedRequestMoneypayload with the originalreportIDwithout 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.
- In production logs across affected users,
-
Uncached Policy Permissions in
canAddTransaction("Permissions required to create expense"):- In
src/libs/ReportUtils.ts:
Whenconst policy = policyParam?.id && policyParam.id === moneyRequestReport?.policyID ? policyParam : getPolicy(moneyRequestReport?.policyID); if (policy && !canCreateExpensesOnPolicy(policy)) { return false; }policyParamis omitted and the local policy collection in Onyx has not yet finished hydrating,policyevaluates toundefined. Becausepolicyis falsy, thecanCreateExpensesOnPolicy(policy)guard evaluates tofalse(bypassing the check), andcanAddTransactionreturnstrue. The client enables the expense creation flow and sendsRequestMoney, which the backend immediately rejects with:"You do not have the permissions required to create expense on this policy."
- In
-
Generic Sentry Grouping in
trackExpenseCreationError.ts:- In
src/libs/telemetry/trackExpenseCreationError.ts, allRequestMoney → 666responses are grouped under the single generic title"Expense API Error: RequestMoney returned 666", mixing expected permission boundaries with genuine replay races.
- In
What changes do you think we should make in order to solve the problem?
-
Pre-flight & Re-route Handling in
src/libs/actions/IOU/MoneyRequestBuilder.ts&SequentialQueue.ts:- In
SequentialQueue, before replayingWRITE_COMMANDS.REQUEST_MONEYfollowing a 407 re-authentication pause: Verify that the targetreport(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
reportIDbefore 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.
- In
-
Harden
canAddTransactioninsrc/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; } }
- When checking policy permissions on workspace expense reports, defensively require that the policy is defined before authorizing expense creation:
-
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.
- Tag Sentry events with specific sub-categories (
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
- 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-5WYor error 666.
- Permission Boundary:
- Sign in as an auditor or member without submit permissions.
- Verify that expense creation is disabled on that policy and
canAddTransactionreturnsfalse.
- 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
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
🤖 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.
| Step | Status |
|---|---|
Ordinary manual expense creationBlocked before submission by overlapping creation/location dialogs. This is a testing blocker, not confirmation of the reported defect.![]() |
❌ |
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.
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:
-
Monolithic Sentry Grouping & Lack of Error Reason Fingerprinting (
trackExpenseCreationError.ts): Insrc/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
RequestMoneycalls that fail withjsonCode: 666,eventMessageis statically formatted asExpense 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,tagsomit the rejection reason or normalized message, and no customfingerprintis provided. -
Misleading Receipt Upload Error Masking & Infinite Retry Loop (
MoneyRequestBuilder.ts&OnyxUpdates.ts): WhenRequestMoneyreturnsjsonCode !== 200(such as666),OnyxUpdates.tsexecutes:if (response.jsonCode !== 200 && request.failureData) { trackExpenseApiError({ ... }); return updateHandler(request.failureData); }In
src/libs/actions/IOU/MoneyRequestBuilder.ts(lines 1076–1105),failureDataapplies: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),getReceiptErrorunconditionally wraps the failure intoCONST.IOU.RECEIPT_ERROR("Receipt upload failed. Tap to retry") withretryParams.- 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
RequestMoneywith the exact same invalid report ID or policy ID, failing repeatedly and re-triggering telemetry. - Tapping "Delete/Dismiss" in
MoneyRequestReceiptView.tsxtriggerstrackExpenseCreationError(null, { ... }), sending yet another redundant Sentry event.
- The server's actual error message (
-
Pre-flight Permission Verification Gap (
useRequestMoneySubmission.ts): Insrc/pages/iou/request/step/confirmation/submission/useRequestMoneySubmission.ts,requestMoneyvalidates 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." -
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 wheremoneyRequestReportIDis pinned), the client dispatchesRequestMoneytargeting the existing report ID. The server rejects the write with code 666: "New expenses cannot be added to this report." -
Clarification on "Possible Lost Expense": The wording
(possible lost expense)in telemetry code strictly belongs toWRITE_COMMANDS.OPEN_REPORT(where an expense report failed to open and might leave an expense unassociated). InRequestMoney → 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?
-
Disaggregate Sentry Telemetry by Rejection Reason and Set Fingerprint (
trackExpenseCreationError.ts):- Extract and normalize the backend rejection reason from
response.messageorextra.message. - Add a
rejection_reasontag and a custom Sentry fingerprint[command, String(jsonCode), normalizedReason]so distinct rejections (e.g.policy_permission_deniedvsreport_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], }); } - Extract and normalize the backend rejection reason from
-
Fix Error Surfacing and Prevent False Receipt Error Masking (
MoneyRequestBuilder.ts&OnyxUpdates.ts):- In
OnyxUpdates.ts, when applyingfailureData, passresponse.messageinto the failure handler or store it intransaction.errors/reportAction.errors. - In
MoneyRequestBuilder.ts: Do not assignCONST.IOU.RECEIPT_ERRORwhenRequestMoneyfails 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
iouReportIDfrom the transaction error recovery so retrying provisions a fresh open report instead of re-targeting the closed report.
- In
-
Add Pre-flight Permission Guard in
useRequestMoneySubmission.ts:- In
useRequestMoneySubmission.ts, verifycanCreateExpensesOnPolicy(policy)before callingrequestMoneyIOUActions. If false, display an error alert and halt submission before making an invalid API write.
- In
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?
- In
tests/unit/trackExpenseCreationErrorTest.ts:- Unit test verifying that
trackExpenseApiErroraddsrejectionReasontag and customfingerprintforRequestMoney → 666responses 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 forOpenReportand never forRequestMoney.
- Unit test verifying that
- In
tests/unit/useRequestMoneySubmissionTest.ts:- Verify that
requestMoneydoes not fireWRITE_COMMANDS.REQUEST_MONEYwhen the user lacks create-expense permissions on the destination workspace policy.
- Verify that
- In
tests/unit/MoneyRequestBuilderTest.ts:- Verify that
failureDataforRequestMoneydoes not wrap non-receipt server validation errors intoCONST.IOU.RECEIPT_ERROR.
- Verify that
— submitted with Antigravity on the contributor's behalf
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Hi I am contributor from Callstack and I would like to help investigating the issue
Hi @kacper-mikolajczak, thanks, assigning you!
📣 @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!
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:
RequestMoneyfails with 407AuthTokenExpired.- 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!
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:
-
Uncached/Omitted Policy in
canAddTransaction(src/libs/ReportUtils.ts): Insrc/libs/ReportUtils.ts:const policy = policyParam?.id && policyParam.id === moneyRequestReport?.policyID ? policyParam : getPolicy(moneyRequestReport?.policyID); if (policy && !canCreateExpensesOnPolicy(policy)) { return false; }When
policyParamis omitted and the module-level Onyx policy cache is still hydrating (or when user policy role changed),policyevaluates toundefined. Becausepolicyis falsy,!canCreateExpensesOnPolicy(policy)is bypassed, andcanAddTransactionreturnstrue. The frontend displays the creation flow and dispatchesRequestMoney, which the backend rejects with: "You do not have the permissions required to create expense on this policy." -
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-sideshouldCreateNewMoneyRequestReportrelies on the local OnyxexistingIOUReport.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." -
Indiscriminate Sentry Error Grouping (
src/libs/telemetry/trackExpenseCreationError.ts): IntrackExpenseCreationError.ts, allRequestMoney → 666responses are captured under Sentry issue APP-5WY with genericExpense API Errortags, 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?
-
Strengthen Pre-Flight Validation in
src/libs/ReportUtils.ts:- In
canAddTransaction: WhenmoneyRequestReport.policyIDis present, defensively verify policy permissions. IfpolicyParamis missing, ensure policy data is resolved and verifycanCreateExpensesOnPolicy(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.
- In
-
Graceful Error Recovery in
src/libs/actions/IOU/MoneyRequestBuilder.ts& Onyx Data:- When
RequestMoneyreturns 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.
- When
-
Segment Telemetry in
src/libs/telemetry/trackExpenseCreationError.ts:- Tag Sentry events with specific rejection reasons (
permission_deniedvs.report_closed_or_locked) so standard business permission failures do not pollute the Sentry error crash tracker.
- Tag Sentry events with specific rejection reasons (
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:
- Verify
canAddTransactionreturnsfalsewhen the user does not have expense creation permissions on the policy. - Verify
shouldCreateNewMoneyRequestReportreturnstruewhen the existing report is closed or submitted. - Verify that receiving a 666 closed-report error in
MoneyRequestBuilderrecovers 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
:warning: Unable to store contributor details
Details
Auth SetContributorDetails returned an error 401 Contributor details already exist
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?
- In
src/libs/actions/IOU.ts:- Defensive sanitation of expense creation parameters: sanitize
category ?? '',tag ?? '', andmerchant: merchant?.trim() || CONST.TRANSACTION.UNKNOWN_MERCHANT.
- Defensive sanitation of expense creation parameters: sanitize
- 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.
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?
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?
@kacper-mikolajczak has access to the backend
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.
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
- 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.
- Duplicate check before report state: Expensify/Auth#26785
- Rejection reason on the expense: Expensify/Web-Expensify#58616
- 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 |
Hi @kacper-mikolajczak, I'm C+ and doesn't have access to BE, maybe @mountiny can help here?