App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-12-08] [$175] [Sentry: APP-NY2 / APP-NK1] iOS Insights crashes with “Invalid time value”

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

Insights can crash during date-control rendering on iOS HybridApp.

Evidence

  • APP-NY2: 8 events / 6 users; all recorded events were simulator builds.
  • APP-NK1: matching stack, 118 events / 37 users. Production confirmed on App Store build 9.5.23.3 with device.simulator=false.
  • Stack: InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format.
  • The formatter parses yyyy-MM-dd and formats without validating the result. The offending value and its source remain unconfirmed.

Expected: Insights renders without crashing; unsupported date selections are handled safely. Actual: Unhandled RangeError: Invalid time value interrupts rendering. Reproduction: Exact steps are not yet established. Testing: Identify the triggering value, add regression coverage, and verify Insights date presets, custom dates, and restored selections on iOS.

Investigation thread

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

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

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

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

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

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

🤖 Web test steps verification results: ⚠️ partial

Dev NewDot web onboarding completed, but Insights date controls were inaccessible. No iOS verification performed. Overlapping dialogs blocking expense fixture setup

Step Status
Date presets render without Invalid time valueBlocked: Insights displayed an expense-empty state without date controls; overlapping dialogs prevented expense setup.

Preliminary analysis — low confidence in the production trigger.
The reported exception has a clear conditional mechanism: a nonempty, unrecognized date value reaches date-fns parsing, and formatting the resulting invalid date throws. However, neither the actual offending value nor its producer was established.

Supporting code: restored non-preset dates are accepted without validation in insightsFilterParsing.ts:23–38. The display helper forwards them to formatting in SearchUIUtils.ts:6411–6438, which formats the parsed date without checking validity in DateUtils.ts:1155–1161.

Hypothesis challenged: merely selecting a preset omitted from the Insights picker does not explain this failure. Recognition covers every defined preset, not just those offered by the picker (SearchQueryUtils.ts:1093–1102). No supported picker flow producing malformed input was identified.

Next investigation: obtain the affected event’s exact date value and source-mapped release context. Production-event access was unavailable, and equivalence between the inspected commit and release 9.5.23.3 remains unverified. Validating restored dates and testing malformed selections are reasonable resilience measures, but are not yet a verified solution to this incident.
Overlapping dialogs blocking expense fixture setup
❌
Valid custom date/range rendersNot verified: date controls were not reached. This does not demonstrate a custom-date failure.
❌
Reload safely restores date selectionNot attempted: session constraints prohibited reloading because authentication could be lost. Restored-selection behavior remains unverified.
❌

view run

MelvinBot avatar Nov 08 '26 02:11 MelvinBot

Proposal

What is the root cause of that problem?

In src/libs/DateUtils.ts:1155–1158, formatToReadableString parses an incoming date string and immediately formats it without validating whether the parsed result is a valid date:

const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
    const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
    return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
};

When date is not in strict yyyy-MM-dd format (e.g. malformed query string, ISO timestamp, non-standard date format, or empty/corrupt stored filter value), parse(date, 'yyyy-MM-dd', new Date()) returns an Invalid Date object (new Date(NaN)).

In date-fns, passing an Invalid Date to format(parsedDate, ...) throws: RangeError: Invalid time value

In InsightsDateControl.tsx:44–46:

<DropdownButton
    label={label}
    value={getDateDisplayValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, buildDateFormValues(value), translate, dateFnsLocale)}
    ...
/>

getDateDisplayValue calls DateUtils.formatToReadableString(on, dateFnsLocale). Because this runs synchronously inside the component render pass, the unhandled RangeError: Invalid time value immediately crashes the screen.

Furthermore, in src/pages/Insights/insightsFilterParsing.ts:20–35, parseDate extracts equality date filters from search queries. When a custom date value is present in onValue, it checks isSearchDatePreset(on), but if not a preset, it unconditionally sets {date: {on}} without verifying that on represents a parseable, valid date.

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

  1. Harden formatToReadableString in src/libs/DateUtils.ts:1155–1158: Add validation using isValid(parsedDate) (already imported from date-fns on line 35). Also add fallback parsing via parseISO(date) to safely support ISO strings, and fallback to returning the raw date or empty string instead of throwing an unhandled exception:

    /**
     * Converts a date to a string in the format MMMM d, yyyy
     */
    const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
        if (!date) {
            return '';
        }
    
        const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
        if (isValid(parsedDate)) {
            return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
        }
    
        const isoDate = parseISO(date);
        if (isValid(isoDate)) {
            return format(isoDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
        }
    
        return date;
    };
    
  2. Validate custom dates in src/pages/Insights/insightsFilterParsing.ts:24–30: In parseDate, verify that custom on date values represent valid dates before constructing {date: {on}}. If invalid, return undefined so that the dashboard safely falls back to default preset selections:

    const onValue = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString();
    if (onValue) {
        const on = normalizeDatePreset(onValue);
        if (isSearchDatePreset(on)) {
            return {date: {preset: on}};
        }
        const parsed = parse(on, 'yyyy-MM-dd', new Date());
        if (isValid(parsed) || isValid(parseISO(on))) {
            return {date: {on}};
        }
        return undefined;
    }
    
  3. Add unit test coverage in tests/unit/DateUtilsTest.ts: Add tests verifying that DateUtils.formatToReadableString:

    • Correctly formats valid yyyy-MM-dd date strings (e.g. '2026-11-08' -> 'November 8, 2026').
    • Correctly formats ISO date strings (e.g. '2026-11-08T00:00:00.000Z').
    • Gracefully returns empty string when given empty/falsy inputs without throwing.
    • Gracefully returns the raw string without throwing RangeError: Invalid time value when given invalid date strings (e.g. 'invalid-date', 'not-a-date').

What alternative solutions did you explore? (Optional)

  • Wrapping only InsightsDateControl in try/catch: Rejected because getDateDisplayValue in SearchUIUtils.ts is shared across Search and Insights filters. Hardening DateUtils.formatToReadableString addresses the root defect across all current and future consumers.

Tests

  1. Insights Date Control:
    • Open Insights dashboard on iOS HybridApp, Web, or Android.
    • Test date presets (e.g. "Year to date", "Last 30 days", "All time").
    • Test custom single date selection ("On [date]").
    • Verify Insights renders without crashing and displays the formatted date cleanly.
  2. Invalid Date Value Resilience:
    • Navigate to an Insights URL with an invalid date parameter (e.g. ?date=invalid or ?date=2026-99-99).
    • Verify the screen does not crash with RangeError: Invalid time value and safely defaults to valid date rendering.
  3. Unit Tests:
    • Run npm test tests/unit/DateUtilsTest.ts and verify all tests pass.

Contributor details

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

kevinjosh10 avatar Nov 08 '26 02:11 kevinjosh10

Proposal

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

On iOS HybridApp (and any platform when restoring or evaluating Insights filters), rendering InsightsDateControl crashes with an unhandled RangeError: Invalid time value inside InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format.

What is the root cause of that problem?

There are three unvalidated hops in the Insights date-filter parsing and display pipeline where non-yyyy-MM-dd or invalid date values bypass validation (unlike buildFilterFormValuesFromQuery in src/libs/SearchQueryUtils.ts:2155-2177):

  1. parseDate in src/pages/Insights/insightsFilterParsing.ts (lines 23–39) accepts any raw date:, date>=, or date<= token from ONYXKEYS.SEARCH_FILTERS without calling isValidDate or checking preset eligibility:

    function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> | undefined {
        const dateFilters = queryJSON.flatFilters.filter(({key}) => key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE).flatMap(({filters}) => filters);
    
        const onValue = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString();
        if (onValue) {
            const on = normalizeDatePreset(onValue);
            return {date: isSearchDatePreset(on) ? {preset: on} : {on}};
        }
    
        const from = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO)?.value.toString();
        const to = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO)?.value.toString();
        if (from && to) {
            return {date: {from, to}};
        }
    
        return undefined;
    }
    
    • Compare this with buildFilterFormValuesFromQuery in src/libs/SearchQueryUtils.ts (lines 2157–2166), which explicitly validates every date filter token with isValidDate(filter.value.toString()) || isSearchDatePreset(filter.value.toString()):
      const rangeStartFilter = filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO && isValidDate(filter.value.toString()));
      const rangeEndFilter = filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO && isValidDate(filter.value.toString()));
      const onFilter = filterList.find((filter) => {
          return filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && (isValidDate(filter.value.toString()) || isSearchDatePreset(filter.value.toString()));
      });
      
    • Because parseDate omits isValidDate:
      • Any non-preset date: value stored in nvp_searchFilters.insightsSpend.query or insightsCompliance.query (e.g. a legacy/unindexed preset or non-yyyy-MM-dd string where isSearchDatePreset(on) is false) is returned as {on}, which buildDateFormValues (src/pages/Insights/insightsQueries.ts:24-26) turns into {dateOn: on}.
      • Even if a preset is recognized by isSearchDatePreset (such as CONST.SEARCH.DATE_PRESETS.NEVER or LAST_STATEMENT), InsightsDateControl (src/pages/Insights/controls/InsightsDateControl.tsx:23) only allows getDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false) (which excludes never and last-statement), yet parseDate still accepts them.
      • Similarly, for date>= and date<=, parseDate does not check isValidDate(from) && isValidDate(to) && from <= to.
  2. fromSearchDateValues in src/pages/Insights/insightsFilterParsing.ts (lines 91–103) also omits isValidDate(on):

    const on = values[CONST.SEARCH.DATE_MODIFIERS.ON];
    if (!on) {
        return undefined;
    }
    
    return isSearchDatePreset(on) ? {preset: on} : {on};
    

    Whereas the range branch on line 92 uses getRangeBoundariesFromFormValue, which validates isValidDate(rawFrom) and isValidDate(rawTo) inside parseRangeQueryValue (src/libs/SearchQueryUtils.ts:588-589), the ON branch accepts any non-preset string without checking isValidDate(on) or verifying that a preset is supported by Insights (INSIGHTS_DATE_PRESETS).

  3. getDateDisplayValue (src/libs/SearchUIUtils.ts:6411-6439) and DateUtils.formatToReadableString (src/libs/DateUtils.ts:1158-1161) call date-fns format without validating the parsed Date: In src/libs/SearchUIUtils.ts:6419-6429:

    if (on) {
        parts.push(isSearchDatePreset(on) ? translate(`search.filters.date.presets.${on}`) : `${translate('common.on')} ${DateUtils.formatToReadableString(on, dateFnsLocale)}`);
    }
    

    And in src/libs/DateUtils.ts:1158-1161:

    const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
        const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
        return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
    };
    

    When on (or after / before) is not a valid yyyy-MM-dd date string, parse(date, 'yyyy-MM-dd', new Date()) returns an Invalid Date (NaN), and format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale}) immediately throws RangeError: Invalid time value, crashing InsightsDateControl during render!

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

We should validate date selections at the Insights filter parsing boundary (src/pages/Insights/insightsFilterParsing.ts) so unsupported/invalid dates fall back cleanly to DEFAULT_INSIGHTS_FILTERS.date, AND harden DateUtils.formatToReadableString / getDateDisplayValue so invalid date strings never throw a RangeError during render:

  1. Validate presets and yyyy-MM-dd dates in src/pages/Insights/insightsFilterParsing.ts (parseDate and fromSearchDateValues): Import isValidDate from @libs/ValidationUtils and getDatePresets from @libs/SearchUIUtils, and validate both on and from / to:

    const INSIGHTS_VALID_DATE_PRESETS = new Set<string>(getDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false));
    
    function isInsightsDatePreset(value: string | undefined): value is SearchDatePreset {
        return !!value && INSIGHTS_VALID_DATE_PRESETS.has(value) && isSearchDatePreset(value);
    }
    
    function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> | undefined {
        const dateFilters = queryJSON.flatFilters.filter(({key}) => key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE).flatMap(({filters}) => filters);
    
        const onFilter = dateFilters.find(({operator, value}) => {
            if (operator !== CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO) {
                return false;
            }
            const normalized = normalizeDatePreset(value.toString());
            return isInsightsDatePreset(normalized) || isValidDate(normalized);
        });
        if (onFilter) {
            const on = normalizeDatePreset(onFilter.value.toString());
            return {date: isInsightsDatePreset(on) ? {preset: on} : {on}};
        }
    
        const from = dateFilters.find(({operator, value}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO && isValidDate(value.toString()))?.value.toString();
        const to = dateFilters.find(({operator, value}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO && isValidDate(value.toString()))?.value.toString();
        if (from && to && from <= to) {
            return {date: {from, to}};
        }
    
        return undefined;
    }
    

    And in fromSearchDateValues (lines 91–103):

    function fromSearchDateValues(values: SearchDateValues): InsightsFilters['date'] | undefined {
        const {from, to} = getRangeBoundariesFromFormValue(values[CONST.SEARCH.DATE_MODIFIERS.RANGE]);
        if (from && to && from <= to) {
            return {from, to};
        }
    
        const rawOn = values[CONST.SEARCH.DATE_MODIFIERS.ON];
        if (!rawOn) {
            return undefined;
        }
    
        const on = normalizeDatePreset(rawOn);
        if (isInsightsDatePreset(on)) {
            return {preset: on};
        }
        if (isValidDate(on)) {
            return {on};
        }
    
        return undefined;
    }
    
  2. Guard formatToReadableString in src/libs/DateUtils.ts (lines 1158–1161) and getDateDisplayValue in src/libs/SearchUIUtils.ts (lines 6419–6430): In src/libs/DateUtils.ts:

    const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
        const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
        if (!isValid(parsedDate)) {
            return '';
        }
        return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
    };
    

    And in src/libs/SearchUIUtils.ts (getDateDisplayValue), only push formatted on, after, and before parts when isSearchDatePreset(on) or DateUtils.formatToReadableString(...) returns a non-empty string:

    if (on) {
        if (isSearchDatePreset(on)) {
            parts.push(translate(`search.filters.date.presets.${on}`));
        } else {
            const formattedOn = DateUtils.formatToReadableString(on, dateFnsLocale);
            if (formattedOn) {
                parts.push(`${translate('common.on')} ${formattedOn}`);
            }
        }
    }
    
    if (after) {
        const formattedAfter = DateUtils.formatToReadableString(after, dateFnsLocale);
        if (formattedAfter) {
            parts.push(`${translate('common.after')} ${formattedAfter}`);
        }
    }
    
    if (before) {
        const formattedBefore = DateUtils.formatToReadableString(before, dateFnsLocale);
        if (formattedBefore) {
            parts.push(`${translate('common.before')} ${formattedBefore}`);
        }
    }
    
  3. Add unit test coverage: Add unit tests in tests/unit/InsightsFilterParsingTest.ts and tests/unit/SearchUIUtilsTest.ts covering:

    • parseInsightsFilters with valid presets (this-year, year-to-date normalized to this-year), valid date:2026-05-01, valid ranges date>=2026-01-01 date<=2026-03-31, and invalid/unsupported stored dates (date:invalid, date:never, inverted ranges date>=2026-05-01 date<=2026-01-01) falling back cleanly to undefined so defaultFilters.date is used.
    • getDateDisplayValue and DateUtils.formatToReadableString returning '' instead of throwing RangeError: Invalid time value when given a malformed date string.

What alternative solutions did you explore?

We considered only guarding DateUtils.formatToReadableString to return '' on invalid dates. However, if parseDate in insightsFilterParsing.ts still accepts an invalid or unsupported date token from a restored query in ONYXKEYS.SEARCH_FILTERS, filters.date would hold a broken {on: ...} object, causing InsightsDateControl to render an empty value label and getInsightsGroupByOptions / buildInsightsQueryString to query with a malformed date filter instead of falling back to DEFAULT_INSIGHTS_FILTERS.date (THIS_YEAR). Validating in both insightsFilterParsing.ts and DateUtils.formatToReadableString / getDateDisplayValue prevents both the crash and corrupted filter state.

zaidrain06 avatar Nov 08 '26 02:11 zaidrain06

Proposal

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

On iOS HybridApp (confirmed in production on App Store build 9.5.23.3 via Sentry APP-NK1 with 118 events / 37 users, and APP-NY2 on simulator builds), opening or rendering the Insights dashboard crashes with an unhandled RangeError: Invalid time value along the call stack InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format.

What is the root cause of that problem?

  1. Exact triggering value and source in production build 9.5.23.3 (date:this-year and newly added presets in server-synced ONYXKEYS.SEARCH_FILTERS):

    • In App Store build 9.5.23-3, CONST.SEARCH.DATE_PRESETS in src/CONST/index.ts only contained 6 values (never, last-month, this-month, year-to-date, last-12-months, last-statement).
    • Subsequent commits on Web/NewDot (specifically PR #104074 / a4032aa21c and the expanded date presets in src/CONST/index.ts) added 9 new presets (this-year, last-year, this-quarter, last-quarter, this-week, last-week, last-30-days, last-90-days, last-6-months) and changed DEFAULT_INSIGHTS_FILTERS.date from {preset: 'year-to-date'} to {preset: 'this-year'}.
    • Whenever a user opens Insights on Web (or a newer client), getInsights / saveInsightsFilters persists the dashboard filter query (e.g. groupBy:month groupCurrency:USD date:this-year or date:last-30-days) into the server-synced NVP ONYXKEYS.SEARCH_FILTERS (nvp_searchFilters.insightsSpend.query / nvp_searchFilters.insightsCompliance.query).
    • When that user opens the iOS HybridApp on 9.5.23.3 (or whenever nvp_searchFilters contains an unrecognized preset or malformed date: value), parseDate in src/pages/Insights/insightsFilterParsing.ts:23-39 runs:
      function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> | undefined {
          const dateFilters = queryJSON.flatFilters.filter(({key}) => key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE).flatMap(({filters}) => filters);
      
          const onValue = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString();
          if (onValue) {
              const on = normalizeDatePreset(onValue);
              return {date: isSearchDatePreset(on) ? {preset: on} : {on}};
          }
      
          const from = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO)?.value.toString();
          const to = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO)?.value.toString();
          if (from && to) {
              return {date: {from, to}};
          }
      
          return undefined;
      }
      
    • Because parseDate does not validate isValidDate(on) when isSearchDatePreset(on) is false (unlike buildFilterFormValuesFromQuery in src/libs/SearchQueryUtils.ts:2157-2165, which checks isValidDate(filter.value.toString()) || isSearchDatePreset(filter.value.toString())), any unrecognized preset or non-yyyy-MM-dd string (such as 'this-year' on 9.5.23.3) is returned as a single-day filter {date: {on: 'this-year'}}.
  2. Unvalidated from / to and fromSearchDateValues in src/pages/Insights/insightsFilterParsing.ts:

    • In parseDate (lines 32-36), from and to are also not validated with isValidDate(from) && isValidDate(to) && from <= to.
    • Furthermore, parseDate and fromSearchDateValues (lines 91-103) check isSearchDatePreset(on) rather than checking whether the preset is actually supported by Insights (INSIGHTS_DATE_PRESETS = getDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false) in InsightsDateControl.tsx:23, which excludes never and last-statement).
  3. Unvalidated parse -> format in DateUtils.formatToReadableString (src/libs/DateUtils.ts:1158-1161):

    • When InsightsDateControl (src/pages/Insights/controls/InsightsDateControl.tsx:45) calls getDateDisplayValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, buildDateFormValues(value), translate, dateFnsLocale), getDateDisplayValue (src/libs/SearchUIUtils.ts:6419-6429) passes on to DateUtils.formatToReadableString(on, dateFnsLocale):
      const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
          const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
          return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
      };
      
    • parse('this-year', 'yyyy-MM-dd', new Date()) returns an Invalid Date (NaN), and date-fns format(parsedDate, ...) immediately throws RangeError: Invalid time value during render.

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

  1. Validate date presets and yyyy-MM-dd calendar dates in src/pages/Insights/insightsFilterParsing.ts:
    • Check presets against the Insights-supported date presets (getDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false)) and validate custom single dates (on) and range bounds (from, to) with isValidDate from @libs/ValidationUtils. When a stored query contains an unsupported preset or invalid date string, parseDate returns undefined so useInsightsFilters cleanly falls back to DEFAULT_INSIGHTS_FILTERS.date ({preset: CONST.SEARCH.DATE_PRESETS.THIS_YEAR}).
  2. Guard formatToReadableString in src/libs/DateUtils.ts and getDateDisplayValue in src/libs/SearchUIUtils.ts:
    • Check if (!isValid(parsedDate)) { return ''; } in formatToReadableString (matching getSplitDateRangeDisplayValue right above it at DateUtils.ts:1145), and only append on / after / before labels in getDateDisplayValue when formatToReadableString returns a non-empty string.
  3. Add unit tests in tests/unit/insightsFilterParsingTest.ts and tests/unit/DateUtilsTest.ts covering unrecognized presets, invalid yyyy-MM-dd strings (e.g. date:invalid, date:2026-02-31), and inverted ranges.

What alternative solutions did you explore? (Optional)

  • Only guarding DateUtils.formatToReadableString without validating in insightsFilterParsing.ts: If parseDate still returns {date: {on: '<invalid>'}} for an unrecognized preset or malformed date token in ONYXKEYS.SEARCH_FILTERS, InsightsDateControl would render a blank label and getInsightsGroupByOptions / buildInsightsQueryString would treat the invalid string as a single-day filter instead of falling back to DEFAULT_INSIGHTS_FILTERS.date (THIS_YEAR). Validating in insightsFilterParsing.ts and guarding formatToReadableString fixes both the crash and the filter fallback.

cocvn157 avatar Nov 08 '26 04:11 cocvn157

📣 @cocvn157! 📣 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 08 '26 04:11 melvin-bot[bot]

@MelvinBot can you create proposal for this issue?

mountiny avatar Nov 08 '26 05:11 mountiny

Proposal

What is the root cause of that problem?

Insights accepts an unrecognized restored date token as a literal calendar date. Rendering then parses it as yyyy-MM-dd and formats the result without checking validity, which can throw RangeError: Invalid time value.

A cross-version preset mismatch is plausible: release 9.5.23-3 does not recognize this-year, while newer clients use it. However, the actual production input remains unconfirmed; this-year is a supported example of the failure mechanism, not a verified incident value.

Code evidence

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

  1. Validate incoming Insights dates. Preserve recognized presets and existing alias normalization. Accept literal dates and range boundaries only when the existing calendar-date validator accepts them.
  2. Use existing fallback behavior. Omit invalid restored date selections so the dashboard default applies, preserving other saved filters. Reject invalid picker values so the previous valid selection remains.
  3. Prevent rendering exceptions. Check the parsed date before formatting; return an empty display value when invalid. Only append “On”, “After”, or “Before” labels when formatting produced a value.
  4. Add regression coverage for unknown presets, impossible dates, invalid range boundaries, default restoration, and omission of dangling labels. Preserve valid dates, leap days, ranges, localized output, and recognized presets.
Implementation boundaries

What alternative solutions did you explore? (Optional)

  • Formatter-only fallback: contains the exception but leaves an invalid filter in query state.
  • Accept ISO timestamps or display raw input: broadens behavior without evidence that these are legitimate inputs.
  • Restrict presets to picker options: unnecessary for this crash; recognized presets already bypass literal-date formatting.

Validation limitation: This is a defensive proposal for a source-supported failure path, not a confirmed correction of the production input’s source. Before treating it as the incident solution, capture the failing value and verify it against the affected release. No new runtime tests were performed for this proposal.


Next Steps for Contributor+ team: To accept: After confirming the production trigger, use @MelvinBot implement [this](https://github.com/Expensify/App/issues/106314) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Nov 08 '26 05:11 MelvinBot

Proposal

What is the root cause of that problem?

src/libs/DateUtils.ts:1158-1161 — formatToReadableString parses with parse(date, 'yyyy-MM-dd', new Date()) and passes the result straight to format(), with no validity check:

const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
    const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
    return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
};

In date-fns, format() on an Invalid Date throws RangeError: Invalid time value.

The crash path is synchronous in render: src/pages/Insights/controls/InsightsDateControl.tsx renders getDateDisplayValue(...), and src/libs/SearchUIUtils.ts:6419-6420 calls DateUtils.formatToReadableString(on, dateFnsLocale) whenever on is not a recognised preset — so one bad value kills the whole Insights screen. The same unguarded call also serves the after and before values (SearchUIUtils.ts:6424, 6428).

The trigger the issue leaves unconfirmed is a stale value in a restored selection: src/pages/Insights/insightsFilterParsing.ts parseDate takes any non-preset on value from a stored dashboard query and keeps it as {date: {on}} with no validity check. normalizeDatePreset (src/libs/SearchQueryUtils.ts:1100-1102) only maps one deprecated preset ("Year to date" → "This year"), so any other legacy preset name — or a malformed date in a shared/bookmarked Insights URL — reaches on verbatim, and the next render throws. That matches the Sentry split: APP-NK1 is 118 events / 37 users on a production App Store build, i.e. real restored dashboards, not just simulator noise.

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

  1. Harden formatToReadableString in src/libs/DateUtils.ts:1158-1161 (fixes every consumer at once, including the after/before paths): return '' for falsy input; if isValid(parse(date, 'yyyy-MM-dd', new Date())), format it; else try parseISO(date) and format if valid; else return the raw string instead of throwing. isValid and parseISO are already imported in this file (lines 35, 38).

  2. Validate in parseDate (src/pages/Insights/insightsFilterParsing.ts): only store {date: {on}} when on is a valid yyyy-MM-dd date or a valid ISO date; otherwise drop the date filter so the dashboard falls back to its default preset instead of crashing on a restored selection.

  3. Add unit tests in tests/unit/DateUtilsTest.ts: valid yyyy-MM-dd formats correctly; ISO strings format correctly; empty input returns '' without throwing; invalid strings ('invalid-date', '2026-99-99') and a stale preset name return the raw string without throwing. Plus a parsing test: a stored Insights query carrying an unparseable on value yields no date filter.

Tests

  1. Insights Date Control: open the Insights dashboard on iOS HybridApp, Web, and Android. Test date presets, a custom single ("On") date, and a restored dashboard whose saved query carries a stale preset value. Verify Insights renders without crashing and the date displays cleanly.
  2. Invalid Date Value Resilience: navigate to an Insights URL with an invalid date parameter (e.g. ?date=invalid, ?date=2026-99-99). Verify the screen does not crash and safely falls back to the default preset.
  3. Unit Tests: run npm test tests/unit/DateUtilsTest.ts and verify all tests pass.

khizzcr7 avatar Nov 08 '26 06:11 khizzcr7

Proposal

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

On iOS HybridApp (and across all platforms when rendering Insights or Search date controls with restored or cross-version date filters), the app crashes during render with an unhandled exception: RangeError: Invalid time value Stack trace: InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format Confirmed via Sentry issues APP-NY2 (simulator) and APP-NK1 (production App Store build 9.5.23.3 with 118 events across 37 users).

What is the root cause of that problem?

The crash is caused by an unvalidated parse-and-format chain combined with permissive date filter restoration:

  1. Unchecked date-fns/format execution in src/libs/DateUtils.ts:1062-1065:

    const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
        const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
        return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
    };
    

    parse(date, 'yyyy-MM-dd', new Date()) from date-fns does not throw when provided with an invalid or unexpected string (such as an unrecognized preset token, a datetime string with timestamps, or malformed user input). Instead, it returns an Invalid Date object whose time value is NaN. format(parsedDate, ...) is called directly without verifying whether parsedDate is valid. date-fns/format throws RangeError: Invalid time value when called on an invalid date, unceremoniously crashing the React render tree.

  2. Permissive date token classification in src/pages/Insights/insightsFilterParsing.ts:14-17:

    const on = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString();
    if (on) {
        return {date: isSearchDatePreset(on) ? {preset: on} : {on}};
    }
    

    If a restored, deep-linked, or cross-version query contains an on value that is not recognized by the current version's isSearchDatePreset (or contains malformed text), parseDate assumes it must be a literal date and packages it as {on}. This is then passed to getDateDisplayValue in SearchUIUtils.ts:5743:

    parts.push(isSearchDatePreset(on) ? translate(`search.filters.date.presets.${on}`) : `${translate('common.on')} ${DateUtils.formatToReadableString(on, dateFnsLocale)}`);
    

    This immediately passes the invalid string into formatToReadableString, crashing InsightsDateControl.

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

  1. Defensively validate parsed dates in src/libs/DateUtils.ts: Import isValid from date-fns and verify the parsed date before formatting:

    --- a/src/libs/DateUtils.ts
    +++ b/src/libs/DateUtils.ts
    @@ -1,7 +1,7 @@
     import {
         addDays,
         addHours,
    +    isValid,
         parse,
         format,
         ...
    @@ -1062,4 +1062,8 @@
     const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
    +    if (!date) {
    +        return '';
    +    }
         const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
    +    if (!isValid(parsedDate)) {
    +        return date;
    +    }
         return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
     };
    

    If parsing yields an invalid date, formatToReadableString safely returns the raw string date rather than throwing RangeError: Invalid time value. This protects all callers across the app (including InsightsDateControl, SearchUIUtils, and CardUtils).

  2. Validate literal calendar dates in src/pages/Insights/insightsFilterParsing.ts: Ensure on, from, and to are valid calendar dates before treating them as custom date filters:

    --- a/src/pages/Insights/insightsFilterParsing.ts
    +++ b/src/pages/Insights/insightsFilterParsing.ts
    @@ -14,6 +14,12 @@ function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> |
         const on = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString();
         if (on) {
    -        return {date: isSearchDatePreset(on) ? {preset: on} : {on}};
    +        if (isSearchDatePreset(on)) {
    +            return {date: {preset: on}};
    +        }
    +        const parsed = parse(on, 'yyyy-MM-dd', new Date());
    +        if (isValid(parsed) && CONST.DATE.REGEX.DATE.test(on)) {
    +            return {date: {on}};
    +        }
    +        return undefined;
         }
    

    This prevents unknown or corrupted date tokens from masquerading as custom dates in filter state.

What alternative solutions did you explore? (Optional)

  • Wrapping format in a try...catch block inside formatToReadableString: While a try...catch prevents unhandled crashes, explicit isValid(parsedDate) checking is faster, idiomatic for date-fns, and avoids relying on exception handling for standard input validation.
  • Only fixing insightsFilterParsing.ts: Rejected because formatToReadableString is a public utility in DateUtils.ts used by multiple features (such as CardUtils.ts and SearchUIUtils.ts). A utility that crashes the UI when given unexpected input represents an architectural liability that must be hardened at the source.

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

In tests/unit/DateUtilsTest.ts:

  • Verify DateUtils.formatToReadableString returns formatted date for valid yyyy-MM-dd.
  • Verify DateUtils.formatToReadableString returns the input string without throwing for invalid inputs (e.g. 'invalid-date', 'last-month', '2024-13-45', '').

In tests/unit/insightsFilterParsingTest.ts:

  • Verify parseDate correctly parses valid presets (this-month), valid calendar dates (2026-11-08), and safely handles/rejects corrupted or unrecognized tokens without crashing.

Contributor details

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

ayolyn avatar Nov 08 '26 14:11 ayolyn

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

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

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

Proposal

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

On iOS HybridApp (as tracked by Sentry issues APP-NY2 and APP-NK1), opening Insights crashes with an unhandled exception: RangeError: Invalid time value.

What is the root cause of that problem?

In src/libs/DateUtils.ts, formatToReadableString formats a date string using:

const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
    const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
    return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
};
  1. When date is undefined, empty, or not in valid yyyy-MM-dd calendar format, date-fns/parse returns an invalid Date object (isNaN(parsedDate.getTime())).
  2. Calling date-fns/format(parsedDate, ...) with an invalid Date object immediately throws RangeError: Invalid time value.
  3. In src/pages/Insights/insightsFilterParsing.ts (parseDate), if an on, from, or to date parameter in queryJSON is not recognized as a preset by isSearchDatePreset(), it is packaged as {date: {on}} without verifying whether it is a valid calendar date format.
  4. When InsightsDateControl passes this unvalidated string through getDateDisplayValue in SearchUIUtils.ts to DateUtils.formatToReadableString(), the unhandled RangeError crashes the component during rendering on iOS.

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

  1. Defensively harden formatToReadableString in src/libs/DateUtils.ts: Import isValid from date-fns and validate parsedDate before formatting:

    const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
        if (!date) {
            return '';
        }
        const parsedDate = parse(date, CONST.DATE.FNS_FORMAT_STRING, new Date());
        if (!isValid(parsedDate)) {
            return date;
        }
        return format(parsedDate, CONST.DATE.MONTH_DAY_YEAR_FORMAT, {locale: dateFnsLocale});
    };
    

    If parsing fails or produces an invalid date, formatToReadableString safely returns the raw string date rather than throwing an unhandled RangeError: Invalid time value. This protects all callers across the app (including InsightsDateControl, SearchUIUtils, and CardUtils).

  2. Validate calendar date strings in src/pages/Insights/insightsFilterParsing.ts: In parseDate(), ensure non-preset on, from, and to values conform to a valid calendar date (e.g. matching CONST.DATE.REGEX.DATE and isValid(parse(val, 'yyyy-MM-dd', new Date()))) before returning them in the filter state. Corrupted or unsupported date values will be safely ignored rather than causing malformed state.

What alternative solutions did you explore? (Optional)

  • Wrapping format in a try...catch block in formatToReadableString: While a try...catch avoids the unhandled crash, explicit isValid(parsedDate) checking is faster, idiomatic for date-fns, and avoids exception handling overhead during component rendering.
  • Only validating inside insightsFilterParsing.ts: Rejected because formatToReadableString is a public utility in DateUtils.ts used by multiple features. Hardening DateUtils.formatToReadableString at the source prevents similar unhandled Sentry crash spikes across the entire codebase.

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

  • In tests/unit/DateUtilsTest.ts:
    • Verify DateUtils.formatToReadableString returns formatted date for valid yyyy-MM-dd dates (e.g., '2026-11-08').
    • Verify DateUtils.formatToReadableString returns the input string without throwing RangeError for invalid inputs (e.g., 'invalid-date', 'last-month', '2024-13-45', '').
  • In tests/unit/insightsFilterParsingTest.ts:
    • Verify parseDate correctly extracts presets, valid calendar dates, and safely handles malformed or unknown date tokens without propagating invalid date state.

happymode-25 avatar Nov 08 '26 16:11 happymode-25

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

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

Proposal

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

On iOS HybridApp (and Simulator), navigating into or rendering the Insights date controls triggers an unhandled RangeError: Invalid time value fatal crash during date display calculation.

What is the root cause of that problem?

In InsightsDateControl (and related date-display helpers such as getDateDisplayValue / formatToReadableString), date strings parsed with date-fns are formatted directly via format(parsedDate, ...) without first validating isValid(parsedDate) or guarding against empty/unrecognized date string formats (e.g. malformed or partial ISO tokens restored from cached selections). When an invalid timestamp or non-ISO token reaches date-fns/format, date-fns throws an unhandled RangeError: Invalid time value, unmounting the component tree.

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

  1. In getDateDisplayValue (or the underlying date formatting utility), parse the input using parseISO / new Date(value) and add an explicit isValid(parsedDate) validation guard.
  2. If !isValid(parsedDate), safely fallback to the current default date preset (or localized fallback string) instead of invoking format().
  3. Add unit tests for getDateDisplayValue verifying that null, undefined, empty string, and malformed date strings return the safe fallback without throwing a RangeError.

What alternative solutions did you explore? (Optional)

Wrapping the call in a local try/catch block. However, validating with isValid() from date-fns is cleaner, more idiomatic, and avoids relying on exception handling for standard input validation.

TassioSales avatar Nov 08 '26 18:11 TassioSales

@MelvinBot raise pr then

FitseTLT avatar Nov 11 '26 13:11 FitseTLT

🤖 Web test steps verification results: ❌ fail

Web verification was blocked by a blank page with no accessible controls. Date-safeguard behavior could not be verified in the browser; no iOS coverage was performed. Blank web page with no available controls

Step Status
Insights presets render without Invalid time valueBlocked: snapshots returned no accessible controls; waiting for Insights timed out.
Blank web page with no available controls
❌
Custom single date rendersBlocked: date controls were inaccessible.
❌
Custom range rendersBlocked: date controls were inaccessible.
❌

Created draft PR: Validate Insights dates and omit invalid date labels, assigned to FitseTLT, with PullerBear review requested.

Passed: 269 targeted tests, lint, type checking, Storybook smoke test, and coding-standards review. Full-suite testing timed out; formatting and final spelling verification remain incomplete. These limitations are documented in the draft.


view run · no recording available

MelvinBot avatar Nov 11 '26 14:11 MelvinBot

PR under review

FitseTLT avatar Nov 17 '26 12:11 FitseTLT

@FitseTLT Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

Reviewing pr

FitseTLT avatar Nov 20 '26 22:11 FitseTLT