You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "sadpandajoe (via GitHub)" <gi...@apache.org> on 2026/07/14 22:22:48 UTC

[PR] fix(charts): render time comparison without a time grain [superset]

sadpandajoe opened a new pull request, #42054:
URL: https://github.com/apache/superset/pull/42054

   ### SUMMARY
   
   A time-series chart using a relative time-comparison offset with **no time grain** returns HTTP 400 `Time Grain must be specified when using Time Comparison.` instead of rendering. The validation was introduced as a side effect of #39344, which turned a previously-dead guard into a live one. Before that change, grain-less comparisons didn't error — but they weren't correct either: the join matched current timestamps against historic ones, so the comparison series was silently empty.
   
   This PR replaces the error with an exact alignment, so saved charts that started 400-ing render again — and now with a *correct* comparison series:
   
   - **Grain-less relative offsets are aligned exactly.** The main series' timestamps are shifted by the offset delta (e.g. `-1 year` for "1 year ago") and joined against the offset series' raw timestamps — the same convention `generate_join_column` uses for the grain path, just without truncation. Timestamps with no exact counterpart yield nulls, mirroring the grain-based join. The join uses stringified values so an empty offset series (which materializes join keys as NaN floats) can't crash the merge on a dtype mismatch.
   - **`normalize_time_delta` converts quarters to months** (`"1 quarter ago"` → `{"months": -3}`), since `pd.DateOffset` rejects a `quarters` argument. This also fixes a pre-existing crash for grain-based quarter offsets in `generate_join_column`.
   - **Free-form offsets** (e.g. `"one year ago"`) that don't match `normalize_time_delta`'s digit-only grammar are shifted per-row with `get_past_or_future` — the same parser that shifted the offset query's time range — instead of silently degrading. If the offset can't be interpreted at all, the join falls back to the raw keys and logs a warning.
   - **The query's x-axis label selects the temporal join key**, rather than whichever datetime column happens to come first, so results with multiple datetime columns align on the actual temporal axis.
   - **Column order is preserved** for grain-less joins. `left_join_df`'s `set_index().join().reset_index()` round-trip moves join keys to the front; the original order is restored so chart payloads and CSV exports don't reorder dimensions.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   
   Before: a time-series chart with Time Comparison enabled (e.g. "1 year ago") and Time Grain cleared fails with `Time Grain must be specified when using Time Comparison.`
   After: the chart renders with the comparison series aligned to the shifted timestamps.
   
   ### TESTING INSTRUCTIONS
   
   1. Create a time-series chart (e.g. ECharts Time-series Line) with a temporal x-axis.
   2. Set Time Grain to "None" (clear it).
   3. Enable a Time Comparison / time shift of "1 year ago" (any relative offset).
   4. On master this returns a 400 error; with this PR the chart renders and the comparison series aligns with the main series wherever shifted timestamps match exactly.
   5. Unit coverage: `pytest tests/unit_tests/common/test_time_shifts.py tests/unit_tests/utils/date_parser_tests.py`
   
   ### ADDITIONAL INFORMATION
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [ ] Introduces new feature or API
   - [ ] Removes existing feature or API
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3592996593


##########
superset/models/helpers.py:
##########
@@ -1912,6 +1913,19 @@ def processing_time_offsets(  # pylint: disable=too-many-locals,too-many-stateme
                             outer_from_dttm,
                             outer_to_dttm,
                         )
+                    elif parse_human_timedelta(offset, outer_from_dttm) == timedelta():
+                        # get_past_or_future silently returns the source time
+                        # for offsets it cannot parse; querying with an
+                        # unshifted window would present the current period's
+                        # data as the comparison series.
+                        raise QueryObjectValidationError(
+                            _(
+                                "Unable to interpret the time offset: "
+                                "%(offset)s. Use a relative time such as "
+                                '"1 month ago".',
+                                offset=offset,
+                            )
+                        )

Review Comment:
   **Suggestion:** The validation treats any offset whose parsed delta equals zero as “uninterpretable”, which incorrectly rejects valid offsets such as `0 days ago` (and other expressions that legitimately resolve to no shift for the chosen reference time). This turns a parseable offset into a hard 400 error; instead of using `== timedelta()` as the parseability test, validate by checking whether parsing failed/raised or by using a parser signal that distinguishes “unparseable” from “parsed to zero”. [incorrect condition logic]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Relative time comparison fails for zero-shift offsets.
   - ⚠️ Users cannot request no-change comparison periods.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Create a QueryObject with a time comparison offset that legitimately resolves to zero
   delta (for example, "0 days ago"), so that `query_object.time_offsets` contains ["0 days
   ago"] (see superset/common/query_object.py:107-107, where `time_offsets: list[str]` is
   defined).
   
   2. Execute a chart query that uses this QueryObject via a datasource; in
   superset/models/helpers.py:1803-1810 the datasource calls
   `self.processing_time_offsets(df, query_object, ...)` when `query_object.time_offsets` is
   non-empty, entering `processing_time_offsets` at superset/models/helpers.py:1828.
   
   3. Inside `processing_time_offsets`, for the offset "0 days ago" the code falls into the
   relative-offset branch at superset/models/helpers.py:1888-1907 (the `else` block labeled
   "RELATIVE OFFSET LOGIC"), where `self.is_valid_date(offset)` is False and `offset !=
   "inherit"`, so execution reaches the `elif parse_human_timedelta(offset, outer_from_dttm)
   == timedelta():` guard at lines 1916-1921.
   
   4. The guard calls `parse_human_timedelta(offset, outer_from_dttm)`; per
   superset/utils/date_parser.py:141-154, `parse_human_timedelta` computes
   `get_past_or_future(human_readable, source_time) - source_dttm`, and for phrases like "0
   days ago" parsedatetime returns the same `source_dttm`, yielding `timedelta(0)`. Because
   the code compares this result to `timedelta()` and treats equality as an "uninterpretable"
   offset, it raises `QueryObjectValidationError` with message "Unable to interpret the time
   offset..." (helpers.py:1916-1928), causing the time-comparison request to fail with a 400
   error even though the offset string was parsed successfully to a legitimate zero-shift
   delta.
   ```
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d6167cc6e44a4cc29f5396c09a60eb94&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d6167cc6e44a4cc29f5396c09a60eb94&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/models/helpers.py
   **Line:** 1916:1928
   **Comment:**
   	*Incorrect Condition Logic: The validation treats any offset whose parsed delta equals zero as “uninterpretable”, which incorrectly rejects valid offsets such as `0 days ago` (and other expressions that legitimately resolve to no shift for the chosen reference time). This turns a parseable offset into a hard 400 error; instead of using `== timedelta()` as the parseability test, validate by checking whether parsing failed/raised or by using a parser signal that distinguishes “unparseable” from “parsed to zero”.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=6e4da12217f6ad41c8ca92cbddd6fb191c44c4938219d059ca3dfd5b8e53ac0b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=6e4da12217f6ad41c8ca92cbddd6fb191c44c4938219d059ca3dfd5b8e53ac0b&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4988675311

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | 6be339598187705a93d6219b007bb86db35698dd |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a5871fa91763200084568a8 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-42054--superset-docs-preview.netlify.app](https://deploy-preview-42054--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQyMDU0LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.MgDDHJz6hYascfwlvSHqfATbkl6mjUe5Eaz_WB3jxHw)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DctBDoMgEEDRu8xaIrSKtDfoMaYzY0uiQAZcNI13l91f_PeHonkvDZ4AA7wVE31704YHy1iPIlqlmRZ3MdRH1FhzMh_FmAyzQ6LuWMqWfy_u0uMcFrfiwy3-frPWhmn2AQOcFw) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-42054--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3593004480


##########
superset/models/helpers.py:
##########
@@ -2369,31 +2483,13 @@ def join_offset_dfs(
             time range instead of being truncated to the main series' range. This
             uses an outer join so offset-only rows (e.g. the rest of a prior day when
             the current day is still in progress) are preserved.
+        :param x_axis_label: The query's temporal x-axis label, used to pick the
+            temporal join key when no time grain is set.
         """
         join_column_producer = app.config["TIME_GRAIN_JOIN_COLUMN_PRODUCERS"].get(
             time_grain
         )
-
-        if not time_grain:
-            has_temporal_join_key = any(
-                pd.api.types.is_datetime64_any_dtype(df[key])
-                for key in join_keys
-                if key in df.columns
-            )
-            if has_temporal_join_key:
-                has_relative_offset = any(
-                    not (
-                        self.is_valid_date_range(offset)
-                        and feature_flag_manager.is_feature_enabled(
-                            "DATE_RANGE_TIMESHIFTS_ENABLED"
-                        )
-                    )
-                    for offset in offset_dfs
-                )
-                if has_relative_offset:
-                    raise QueryObjectValidationError(
-                        _("Time Grain must be specified when using Time Comparison.")
-                    )
+        original_columns = list(df.columns)

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag tuple-unpacking assignments in Python for missing inline type annotations when the types are already inferred from an annotated return value.
   
   **Applied to:**
     - `**/*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4997148093

   **Bito Automatic Review Failed - Technical Failure** <br/><br/> Bito encountered technical difficulties while generating code feedback . To retry, type `/review` in a comment and save. If the issue persists, contact support@bito.ai and provide the following details: <br/><br/>Agent Run ID: 67810da5-8efc-4e7d-b956-cdbfbc15bc88


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3590947182


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +563,18 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_normalize_time_delta() -> None:
+    assert normalize_time_delta("1 year ago") == {"years": -1}
+    assert normalize_time_delta("2 months later") == {"months": 2}
+    assert normalize_time_delta("28 days ago") == {"days": -28}
+    # quarters are converted to months (pd.DateOffset has no quarters argument)
+    assert normalize_time_delta("1 quarter ago") == {"months": -3}
+    assert normalize_time_delta("2 quarters later") == {"months": 6}

Review Comment:
   Added coverage for the remaining units (seconds, minutes, hours, weeks) in 6955917680.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4986849527

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3593070973


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +564,70 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)

Review Comment:
   Not changed: `dttm` is initialized with a `datetime(...)` literal, so an annotation adds no information; the file's existing tests (e.g. `test_get_past_or_future`) keep such locals unannotated.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
superset/utils/date_parser.py:
##########
@@ -95,9 +105,12 @@ def normalize_time_delta(human_readable: str) -> dict[str, int]:
     if not matched:
         raise TimeDeltaAmbiguousError(human_readable)
 
-    key = matched[2] + "s"
+    key = matched[2].lower() + "s"

Review Comment:
   Not changed: `key` / `value` are locals whose types are exact from the right-hand expressions (`str.lower() + "s"`, `int(...)`); mypy infers them precisely, and the repo's type-hint rule targets signatures and module-level names, not literal-initialized locals.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +564,70 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)

Review Comment:
   Not changed: same as above — a `datetime(...)`-literal local needs no annotation, matching the file's existing style.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4985573866

   The `unit-tests` failure is unrelated to this PR: test collection errors on `tests/unit_tests/migrations/test_strip_metricsqlexpressions_from_ag_grid_params.py` because the migration it imports uses the deprecated `sqlalchemy.ext.declarative.declarative_base`, which `SQLALCHEMY_WARN_20=1` + the pytest filter turns into an error. Fix is pending in #42080 — will update this branch once it lands.
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3598310413


##########
superset/models/helpers.py:
##########
@@ -2312,8 +2349,110 @@ def _determine_join_keys(
             return self._process_date_range_offset(offset_df, join_keys)
 
         else:
+            return self._align_offset_without_time_grain(
+                df, offset_df, offset, join_keys, x_axis_label
+            )
+
+    def _align_offset_without_time_grain(
+        self,
+        df: pd.DataFrame,
+        offset_df: pd.DataFrame,
+        offset: str,
+        join_keys: list[str],
+        x_axis_label: str | None = None,
+    ) -> tuple[pd.DataFrame, list[str]]:
+        """
+        Determine join keys for a relative offset when no time grain is set.
+
+        Without a time grain there is no truncated join column, but the two
+        series can still be aligned exactly: shifting the main series'
+        timestamps by the offset delta lands them on the offset series' raw
+        timestamps (normalize_time_delta returns a negative delta for "... ago"
+        offsets). Timestamps without an exact counterpart in the offset series
+        produce nulls, mirroring the grain-based join, and null timestamps in
+        the two series join to each other (both stringify to "NaT"). When
+        there is no temporal join key the original join keys are used as-is.
+
+        The shift is computed on wall-clock time, with any timezone dropped for
+        the duration of the alignment. The offset query's own time range was
+        shifted the same way -- ``get_past_or_future`` reads naive timestamps
+        -- so the rows it returns carry the source wall clock, and matching on
+        it is what aligns the two series. Re-localizing the result would only
+        reintroduce the DST edge cases that wall-clock arithmetic sidesteps:
+        shifting onto a skipped or repeated local hour raises out of pandas.
+        Both sides are normalized identically, so the two readings of a
+        repeated hour still align with each other.
+
+        Month, quarter, and year offsets shift via ``DateOffset``, which clamps
+        to a valid calendar day (e.g. Mar 29, 30, and 31 all shift back one
+        month to Feb 28), so on daily/irregular data several end-of-month rows
+        can align to the same offset timestamp. This mirrors the inherent
+        ambiguity of "the same day N months ago" without a time grain to
+        truncate against.
+        """
+        # Prefer the query's temporal x-axis when it is a join key; otherwise
+        # use the first datetime join key.
+        candidate_keys = sorted(join_keys, key=lambda key: key != x_axis_label)
+        temporal_join_key = next(
+            (
+                key
+                for key in candidate_keys
+                if key in df.columns
+                and key in offset_df.columns
+                and pd.api.types.is_datetime64_any_dtype(df[key])

Review Comment:
   **Suggestion:** The temporal-key detection is too strict: it only accepts `datetime64` dtypes from the main DataFrame. Superset can carry temporal columns as `object` series of `datetime.date`/`datetime` values (already treated as temporal elsewhere), and this guard will miss them, fall back to raw join keys, and silently produce empty/misaligned comparison series for grain-less offsets. Use the same temporal detection logic used elsewhere (e.g. `dataframe_utils.is_datetime_series`) so object-backed temporal columns are aligned instead of bypassed. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Grain-less time comparison misaligns temporal comparison series.
   - ⚠️ Some charts show empty comparison results.
   - ⚠️ Object-backed date axes not aligned for offsets.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Execute a time-series chart query through `ExploreMixin.get_query_result`
   (`superset/models/helpers.py:1739-1818`) where `query_object.time_offsets` is non-empty,
   `time_grain` is `None`, and the temporal axis column (e.g. `"ds"`) is included in
   `join_keys` with dtype `object` holding `datetime.date`/`datetime` values (a pattern
   explicitly treated as temporal by `dataframe_utils.is_datetime_series` in
   `superset/common/utils/dataframe_utils.py:72-81`).
   
   2. In `processing_time_offsets` (`superset/models/helpers.py:1839-2143`), the base
   DataFrame `df` is normalized via `normalize_df`, then `join_keys` are built from
   non-metric columns and `join_offset_dfs` is called with `time_grain=None` and those
   `join_keys` when `offset_dfs` has relative offsets populated.
   
   3. Inside `join_offset_dfs` (`superset/models/helpers.py:2492-2570`), the code dispatches
   to `_determine_join_keys`, which in the `else` (grain-less, non-date-range) branch calls
   `_align_offset_without_time_grain` (`superset/models/helpers.py:2356-2475`) with `df`,
   `offset_df`, `offset`, `join_keys`, and `x_axis_label` set to the query’s temporal axis
   label.
   
   4. `_align_offset_without_time_grain` computes `candidate_keys` and then
   `temporal_join_key` using the guard `key in df.columns and key in offset_df.columns and
   pd.api.types.is_datetime64_any_dtype(df[key])` (`superset/models/helpers.py:2398-2405`).
   For an object-typed temporal column containing `datetime.date`/`datetime` values,
   `is_datetime64_any_dtype(df[key])` returns `False`, so `temporal_join_key` is `None` and
   the function returns `offset_df, join_keys` without adding a shifted temporal join column.
   The subsequent join in `_perform_join` (`superset/models/helpers.py:177-205`) operates
   only on the raw non-temporal join keys, causing the grain-less time-comparison series to
   be empty or misaligned instead of aligned on the temporal axis.
   ```
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b47d8329ae0c4d7f8c843d17958f48fc&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b47d8329ae0c4d7f8c843d17958f48fc&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/models/helpers.py
   **Line:** 2402:2402
   **Comment:**
   	*Logic Error: The temporal-key detection is too strict: it only accepts `datetime64` dtypes from the main DataFrame. Superset can carry temporal columns as `object` series of `datetime.date`/`datetime` values (already treated as temporal elsewhere), and this guard will miss them, fall back to raw join keys, and silently produce empty/misaligned comparison series for grain-less offsets. Use the same temporal detection logic used elsewhere (e.g. `dataframe_utils.is_datetime_series`) so object-backed temporal columns are aligned instead of bypassed.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=30d4e86e41cb7f4ccf82dbe6805321650e847870d6689e3b14051151382722b4&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=30d4e86e41cb7f4ccf82dbe6805321650e847870d6689e3b14051151382722b4&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3598275728


##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -1024,6 +1024,159 @@ def fake_query(dct: dict[str, Any]) -> MagicMock:
     assert "2025-06-01" in val, f"Expected shifted-to-dttm in val, got: {val!r}"
 
 
+def test_processing_time_offsets_quarter_offset_shifts_query_window(processor):
+    """A quarter offset must shift the offset query's window, not just the
+    join keys. parsedatetime does not understand "1 quarter ago", so without
+    rewriting quarters to months the offset subquery silently runs against
+    the current period and the comparison series joins to nulls. The fake
+    query below derives its rows from the requested window, so the join only
+    yields the expected values when the window was actually shifted.
+    """
+    from superset.common.query_object import QueryObject
+    from superset.models.helpers import ExploreMixin
+
+    for method in (
+        "processing_time_offsets",
+        "_align_offset_without_time_grain",
+        "_coalesce_offset_index",
+    ):
+        setattr(
+            processor._qc_datasource,
+            method,
+            getattr(ExploreMixin, method).__get__(processor._qc_datasource),
+        )
+
+    df = pd.DataFrame(
+        {
+            "__timestamp": pd.to_datetime(["2024-04-01", "2024-05-01", "2024-06-01"]),
+            "sum__num": [100, 200, 300],
+        }
+    )
+
+    query_object = QueryObject(
+        datasource=MagicMock(),
+        granularity="ds",
+        columns=[],
+        metrics=["sum__num"],
+        is_timeseries=True,
+        time_offsets=["1 quarter ago"],
+        filters=[
+            {
+                "col": "ds",
+                "op": "TEMPORAL_RANGE",
+                "val": "2024-04-01 : 2024-07-01",
+            }
+        ],
+    )
+
+    captured: list[dict[str, Any]] = []
+
+    def fake_query(dct: dict[str, Any]) -> MagicMock:
+        captured.append(dct)
+        result = MagicMock()
+        result.df = pd.DataFrame(
+            {
+                "__timestamp": pd.date_range(
+                    start=dct["from_dttm"], periods=3, freq="MS"
+                ),
+                "sum__num": [1.0, 2.0, 3.0],
+            }
+        )
+        result.query = "SELECT 1"
+        return result
+
+    processor._qc_datasource.query = fake_query
+    processor._qc_datasource.normalize_df = MagicMock(
+        side_effect=lambda offset_df, _query_object: offset_df
+    )
+
+    with (
+        patch(
+            "superset.models.helpers.get_since_until_from_query_object",
+            return_value=(pd.Timestamp("2024-04-01"), pd.Timestamp("2024-07-01")),
+        ),
+        patch(
+            "superset.common.utils.query_cache_manager.QueryCacheManager"
+        ) as mock_cache_manager,
+        patch.object(
+            processor._qc_datasource,
+            "get_time_grain",
+            return_value=None,
+        ),
+    ):
+        mock_cache = MagicMock()
+        mock_cache.is_loaded = False
+        mock_cache_manager.get.return_value = mock_cache
+
+        result = processor._qc_datasource.processing_time_offsets(
+            df, query_object, None, None, False
+        )
+
+    assert len(captured) == 1
+    assert captured[0]["from_dttm"] == pd.Timestamp("2024-01-01")
+    assert captured[0]["to_dttm"] == pd.Timestamp("2024-04-01")
+    assert result["df"]["sum__num__1 quarter ago"].tolist() == [1.0, 2.0, 3.0]
+
+
+def test_processing_time_offsets_rejects_unparseable_offset(processor):

Review Comment:
   Annotated `processor: QueryContextProcessor` in 41eaa741cb, matching the other tests in this file.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4995970966

   🎪 [Showtime](https://github.com/mistercrunch/superset-showtime) deployed environment on [GHA](https://github.com/apache/superset/actions/runs/29528332420) for [47b829d](https://github.com/apache/superset/commit/47b829d)
   
   • **Environment:** http://54.191.82.136:8080 (admin/admin)
   • **Lifetime:** 48h auto-cleanup
   • **Updates:** New commits create fresh environments automatically


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4990045120

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4995813013

   🎪 [Showtime](https://github.com/mistercrunch/superset-showtime) deployed environment on [GHA](https://github.com/apache/superset/actions/runs/29527130454) for [5e4f6b6](https://github.com/apache/superset/commit/5e4f6b6)
   
   • **Environment:** http://35.86.252.225:8080 (admin/admin)
   • **Lifetime:** 48h auto-cleanup
   • **Updates:** New commits create fresh environments automatically


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3598259392


##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -389,8 +391,45 @@ def test_get_offset_custom_or_inherit_with_inherit(processor):
         "inherit", from_dttm, to_dttm
     )
 
-    # Should return the difference in days
-    assert result == "9 days ago"
+    # Should shift back by the length of the range: 9 days, in seconds
+    assert result == "777600 seconds ago"
+
+
+@pytest.mark.parametrize(
+    "hours",
+    [
+        # Sub-day ranges truncated to "0 days ago" and compared the range
+        # against itself.
+        1,
+        12,
+        # Ranges that are not a whole number of days truncated downwards and
+        # overlapped the range they were compared against.
+        36,
+        # Whole-day ranges were already correct and must stay so.
+        24,
+        48,
+    ],
+)
+def test_get_offset_custom_or_inherit_shifts_by_full_range(
+    processor, hours: int
+) -> None:

Review Comment:
   **Suggestion:** Add a type annotation for the `processor` parameter in this new test function signature to satisfy the required type-hint rule. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   The new test function signature omits a type hint for the `processor` parameter, which is directly annotatable. This matches the repository rule requiring type hints on new or modified Python code.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=aeba830e0d5f4bae82e62d05c0d69336&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=aeba830e0d5f4bae82e62d05c0d69336&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_query_context_processor.py
   **Line:** 413:415
   **Comment:**
   	*Custom Rule: Add a type annotation for the `processor` parameter in this new test function signature to satisfy the required type-hint rule.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=9bf5c8a250feeb5d232d62376d4fedc333715874b478dad92914eb358c14be9a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=9bf5c8a250feeb5d232d62376d4fedc333715874b478dad92914eb358c14be9a&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4995671983

   🎪 [Showtime](https://github.com/mistercrunch/superset-showtime) is building environment on [GHA](https://github.com/apache/superset/actions/runs/29527130454) for [5e4f6b6](https://github.com/apache/superset/commit/5e4f6b6)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3593064068


##########
superset/utils/date_parser.py:
##########
@@ -95,9 +105,12 @@ def normalize_time_delta(human_readable: str) -> dict[str, int]:
     if not matched:
         raise TimeDeltaAmbiguousError(human_readable)
 
-    key = matched[2] + "s"
+    key = matched[2].lower() + "s"

Review Comment:
   **Suggestion:** Add an explicit type annotation for the newly introduced local variable so its intended string type is clear. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This newly added local variable is assigned a string value but has no type annotation, which matches the custom rule requiring type hints on newly added or modified Python code where annotation is feasible.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7b6cc692bc4348e7be1e2cd494900eac&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=7b6cc692bc4348e7be1e2cd494900eac&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/utils/date_parser.py
   **Line:** 108:108
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for the newly introduced local variable so its intended string type is clear.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=ced4cb7d31830d099ef9eed8f302c8735081f567c239ae2cd676ebeea3dc525b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=ced4cb7d31830d099ef9eed8f302c8735081f567c239ae2cd676ebeea3dc525b&reaction=dislike'>👎</a>



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +564,70 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)

Review Comment:
   **Suggestion:** Add an explicit type annotation for this local datetime variable to comply with the type-hints requirement. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is a newly added local variable with an obvious datetime type and no annotation. That matches the rule requiring type hints on relevant variables that can be annotated.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=203e4f3100a3414baa831219162cdcac&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=203e4f3100a3414baa831219162cdcac&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/utils/date_parser_tests.py
   **Line:** 570:570
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this local datetime variable to comply with the type-hints requirement.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=b3fb9aea76fbe522056f7f450a51b8df6dddd21acb05c5bebb3751fb6dbe8059&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=b3fb9aea76fbe522056f7f450a51b8df6dddd21acb05c5bebb3751fb6dbe8059&reaction=dislike'>👎</a>



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +564,70 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)

Review Comment:
   **Suggestion:** Add an explicit type annotation for this local datetime variable to satisfy the mandatory typing rule for relevant variables. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is another newly introduced local variable with a clearly inferable datetime type and no type hint, so it violates the Python type-hints rule.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=021474adb8ba4aa692a23668ac732177&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=021474adb8ba4aa692a23668ac732177&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/utils/date_parser_tests.py
   **Line:** 593:593
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this local datetime variable to satisfy the mandatory typing rule for relevant variables.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=9bc8a8dd2e4a74a3e50500ae7a73a9f61d49ba6b632c0f4b53184689c2eb91a0&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=9bc8a8dd2e4a74a3e50500ae7a73a9f61d49ba6b632c0f4b53184689c2eb91a0&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3593001552


##########
superset/utils/date_parser.py:
##########
@@ -66,6 +66,14 @@
     "1st": 1,
 }
 
+# parsedatetime does not understand "N quarters" (it leaves the source time
+# unchanged), so such phrases are rewritten to the equivalent number of months
+# before parsing. The lookbehind and the bounded repetition keep matching
+# linear on user-provided strings (every suffix of an unbounded digit run
+# would be re-scanned) and keep the int() conversion small; longer digit
+# runs fall through to parsedatetime like any other unparseable phrase.
+_QUARTERS_PATTERN = re.compile(r"(?<![0-9])([0-9]{1,10})\s+quarters?\b", re.IGNORECASE)

Review Comment:
   Annotated: `_QUARTERS_PATTERN: re.Pattern[str]` in a5b06005ba.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -1024,6 +1024,159 @@ def fake_query(dct: dict[str, Any]) -> MagicMock:
     assert "2025-06-01" in val, f"Expected shifted-to-dttm in val, got: {val!r}"
 
 
+def test_processing_time_offsets_quarter_offset_shifts_query_window(processor):

Review Comment:
   Annotated `processor: QueryContextProcessor` and `-> None` in a5b06005ba, with a typed `Any` alias for the MagicMock datasource the test binds real methods onto.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -1024,6 +1024,159 @@ def fake_query(dct: dict[str, Any]) -> MagicMock:
     assert "2025-06-01" in val, f"Expected shifted-to-dttm in val, got: {val!r}"
 
 
+def test_processing_time_offsets_quarter_offset_shifts_query_window(processor):
+    """A quarter offset must shift the offset query's window, not just the
+    join keys. parsedatetime does not understand "1 quarter ago", so without
+    rewriting quarters to months the offset subquery silently runs against
+    the current period and the comparison series joins to nulls. The fake
+    query below derives its rows from the requested window, so the join only
+    yields the expected values when the window was actually shifted.
+    """
+    from superset.common.query_object import QueryObject
+    from superset.models.helpers import ExploreMixin
+
+    for method in (
+        "processing_time_offsets",
+        "_align_offset_without_time_grain",
+        "_coalesce_offset_index",
+    ):
+        setattr(
+            processor._qc_datasource,
+            method,
+            getattr(ExploreMixin, method).__get__(processor._qc_datasource),
+        )
+
+    df = pd.DataFrame(
+        {
+            "__timestamp": pd.to_datetime(["2024-04-01", "2024-05-01", "2024-06-01"]),
+            "sum__num": [100, 200, 300],
+        }
+    )
+
+    query_object = QueryObject(
+        datasource=MagicMock(),
+        granularity="ds",
+        columns=[],
+        metrics=["sum__num"],
+        is_timeseries=True,
+        time_offsets=["1 quarter ago"],
+        filters=[
+            {
+                "col": "ds",
+                "op": "TEMPORAL_RANGE",
+                "val": "2024-04-01 : 2024-07-01",
+            }
+        ],
+    )
+
+    captured: list[dict[str, Any]] = []
+
+    def fake_query(dct: dict[str, Any]) -> MagicMock:
+        captured.append(dct)
+        result = MagicMock()
+        result.df = pd.DataFrame(
+            {
+                "__timestamp": pd.date_range(
+                    start=dct["from_dttm"], periods=3, freq="MS"
+                ),
+                "sum__num": [1.0, 2.0, 3.0],
+            }
+        )
+        result.query = "SELECT 1"
+        return result
+
+    processor._qc_datasource.query = fake_query
+    processor._qc_datasource.normalize_df = MagicMock(
+        side_effect=lambda offset_df, _query_object: offset_df
+    )
+
+    with (
+        patch(
+            "superset.models.helpers.get_since_until_from_query_object",
+            return_value=(pd.Timestamp("2024-04-01"), pd.Timestamp("2024-07-01")),
+        ),
+        patch(
+            "superset.common.utils.query_cache_manager.QueryCacheManager"
+        ) as mock_cache_manager,
+        patch.object(
+            processor._qc_datasource,
+            "get_time_grain",
+            return_value=None,
+        ),
+    ):
+        mock_cache = MagicMock()
+        mock_cache.is_loaded = False
+        mock_cache_manager.get.return_value = mock_cache
+
+        result = processor._qc_datasource.processing_time_offsets(
+            df, query_object, None, None, False
+        )
+
+    assert len(captured) == 1
+    assert captured[0]["from_dttm"] == pd.Timestamp("2024-01-01")
+    assert captured[0]["to_dttm"] == pd.Timestamp("2024-04-01")
+    assert result["df"]["sum__num__1 quarter ago"].tolist() == [1.0, 2.0, 3.0]
+
+
+def test_processing_time_offsets_rejects_unparseable_offset(processor):

Review Comment:
   Annotated `processor: QueryContextProcessor` and `-> None` in a5b06005ba, with a typed `Any` alias for the MagicMock datasource the test binds real methods onto.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,19 +337,259 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset() -> None:
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls() -> None:
+    """
+    Without a time grain, offset timestamps that have no exact shifted
+    counterpart in the main series produce nulls instead of raising.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-06-15")], "B": [5]})
+    offset_dfs = {"1 year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_multiple_offsets() -> None:
+    """
+    Multiple relative offsets without a time grain each align on their own
+    shifted timestamps, and no synthetic join columns leak into the result.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-29")], "D": [1]})
+    offset_df1 = DataFrame({"ds": [Timestamp("2021-01-01")], "B": [5]})
+    offset_df2 = DataFrame({"ds": [Timestamp("2020-01-29")], "C": [7]})
+    offset_dfs = {"28 days ago": offset_df1, "1 year ago": offset_df2}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-29")],
+            "D": [1],
+            "B": [5],
+            "C": [7],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_empty_offset_df() -> None:
+    """
+    An empty offset series materializes its join keys as NaN floats; the
+    grain-less join must not crash on the dtype mismatch.
+    """
     df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
-    offset_df = DataFrame({"ds": [Timestamp("2021-02-01")], "B": [5]})
+    offset_df = DataFrame({"ds": [float("nan")], "B": [float("nan")]})
     offset_dfs = {"1 year ago": offset_df}
 
-    with pytest.raises(
-        QueryObjectValidationError, match="Time Grain must be specified"
-    ):
-        query_context_processor.join_offset_dfs(
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_quarter_offset() -> None:
+    """
+    Quarter offsets align without a time grain (normalize_time_delta converts
+    quarters to months, since pd.DateOffset has no quarters argument).
+    """
+    df = DataFrame({"ds": [Timestamp("2021-04-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2021-01-01")], "B": [5]})
+    offset_dfs = {"1 quarter ago": offset_df}
+
+    expected = DataFrame({"ds": [Timestamp("2021-04-01")], "D": [1], "B": [5]})
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_free_form_offset() -> None:
+    """
+    Offsets outside the normalize_time_delta grammar (e.g. "one year ago")
+    are aligned with the same parser that shifted the offset query's range.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-01-01")], "B": [5]})
+    offset_dfs = {"one year ago": offset_df}
+
+    expected = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1], "B": [5]})
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_free_form_offset_tz_microseconds() -> None:
+    """
+    Free-form offsets align timezone-aware, sub-second timestamps: each row's
+    shift is computed from a naive second-truncated copy and applied to the
+    original value, so the join keys keep their timezone and precision.
+    """
+    df = DataFrame(
+        {"ds": [Timestamp("2021-03-04 05:06:07.890123", tz="UTC")], "D": [1]}
+    )
+    offset_df = DataFrame(
+        {"ds": [Timestamp("2020-03-04 05:06:07.890123", tz="UTC")], "B": [5]}
+    )
+    offset_dfs = {"one year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert result["B"].tolist() == [5]
+
+
+def test_join_offset_dfs_no_time_grain_uninterpretable_offset() -> None:
+    """
+    An offset that no parser can interpret falls back to joining on the raw
+    keys (an empty comparison series) instead of crashing.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-01-01")], "B": [5]})
+    offset_dfs = {"not a real offset": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_uninterpretable_offset_subsecond(
+    caplog,
+) -> None:

Review Comment:
   Annotated `caplog: LogCaptureFixture` in a5b06005ba.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
superset/models/helpers.py:
##########
@@ -2369,31 +2483,13 @@ def join_offset_dfs(
             time range instead of being truncated to the main series' range. This
             uses an outer join so offset-only rows (e.g. the rest of a prior day when
             the current day is still in progress) are preserved.
+        :param x_axis_label: The query's temporal x-axis label, used to pick the
+            temporal join key when no time grain is set.
         """
         join_column_producer = app.config["TIME_GRAIN_JOIN_COLUMN_PRODUCERS"].get(
             time_grain
         )
-
-        if not time_grain:
-            has_temporal_join_key = any(
-                pd.api.types.is_datetime64_any_dtype(df[key])
-                for key in join_keys
-                if key in df.columns
-            )
-            if has_temporal_join_key:
-                has_relative_offset = any(
-                    not (
-                        self.is_valid_date_range(offset)
-                        and feature_flag_manager.is_feature_enabled(
-                            "DATE_RANGE_TIMESHIFTS_ENABLED"
-                        )
-                    )
-                    for offset in offset_dfs
-                )
-                if has_relative_offset:
-                    raise QueryObjectValidationError(
-                        _("Time Grain must be specified when using Time Comparison.")
-                    )
+        original_columns = list(df.columns)

Review Comment:
   Not changed: the flagged line is a tuple-unpacking assignment (`offset_df, actual_join_keys = ...`), which cannot carry an inline annotation in Python; both types are fully inferred from `_determine_join_keys`'s annotated return type.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3591002873


##########
superset/utils/date_parser.py:
##########
@@ -98,6 +98,9 @@ def normalize_time_delta(human_readable: str) -> dict[str, int]:
     key = matched[2] + "s"
     value = int(matched[1])
     value = -value if matched[3] == "ago" else value
+    if key == "quarters":
+        # pd.DateOffset does not accept a `quarters` argument
+        key, value = "months", value * 3

Review Comment:
   Good catch — fixed in 6d5373d7d1: the unit key and the ago/later direction are both lowercased before comparison (the direction check had the same case bug, silently shifting forward for "1 year AGO"), with regression assertions added.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4985825881

   Status update on the unrelated CI failures: the `declarative_base` collection error is already fixed on master (#42056 landed), so unit-tests collection now succeeds. The remaining 3 unit-test failures and the pre-commit failure are all the `semantic_layers/mapper.py` duplicate `_get_time_axis_column` master breakage, fixed by the pending #42093. This PR's own tests all pass (10240 passed otherwise). I'll update the branch once #42093 lands.
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3590956425


##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():

Review Comment:
   **Suggestion:** Add an explicit return type annotation to this new test function to comply with the required typing standard. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is a newly added Python test function with no return type annotation, which violates the type-hint requirement for new or modified Python code.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b095c8f061834f93825e4edb73566e67&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b095c8f061834f93825e4edb73566e67&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_time_shifts.py
   **Line:** 338:338
   **Comment:**
   	*Custom Rule: Add an explicit return type annotation to this new test function to comply with the required typing standard.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=1483d10a595871e521342238427b09174a962b7c84d34effe101469b52e7641b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=1483d10a595871e521342238427b09174a962b7c84d34effe101469b52e7641b&reaction=dislike'>👎</a>



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls():
+    """
+    Without a time grain, offset timestamps that have no exact shifted
+    counterpart in the main series produce nulls instead of raising.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-06-15")], "B": [5]})
+    offset_dfs = {"1 year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_multiple_offsets():

Review Comment:
   **Suggestion:** Add an explicit return type annotation to this newly introduced test function. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   The new test function has no return type annotation, which is a real violation of the project rule requiring type hints on newly added Python code.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b004f3da51ad4ed385bae194ac5012f0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b004f3da51ad4ed385bae194ac5012f0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_time_shifts.py
   **Line:** 390:390
   **Comment:**
   	*Custom Rule: Add an explicit return type annotation to this newly introduced test function.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=2140ed9c8910a98439194fe3e78beb21c9d839fbccb16425cffa4d97789bc48f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=2140ed9c8910a98439194fe3e78beb21c9d839fbccb16425cffa4d97789bc48f&reaction=dislike'>👎</a>



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls():

Review Comment:
   **Suggestion:** Add an explicit return type annotation to this new test function to satisfy the mandatory type-hint rule. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This newly introduced test function omits a return type annotation, so it matches the custom rule requiring type hints on new Python functions.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=95017e6bc80e4a7cbc812758cb79726e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=95017e6bc80e4a7cbc812758cb79726e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_time_shifts.py
   **Line:** 373:373
   **Comment:**
   	*Custom Rule: Add an explicit return type annotation to this new test function to satisfy the mandatory type-hint rule.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=f75987b06fc6fe44a6151e32e84fe690850e2758b66d96d16dbf076611205bec&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=f75987b06fc6fe44a6151e32e84fe690850e2758b66d96d16dbf076611205bec&reaction=dislike'>👎</a>



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls():
+    """
+    Without a time grain, offset timestamps that have no exact shifted
+    counterpart in the main series produce nulls instead of raising.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-06-15")], "B": [5]})
+    offset_dfs = {"1 year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_multiple_offsets():
+    """
+    Multiple relative offsets without a time grain each align on their own
+    shifted timestamps, and no synthetic join columns leak into the result.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-29")], "D": [1]})
+    offset_df1 = DataFrame({"ds": [Timestamp("2021-01-01")], "B": [5]})
+    offset_df2 = DataFrame({"ds": [Timestamp("2020-01-29")], "C": [7]})
+    offset_dfs = {"28 days ago": offset_df1, "1 year ago": offset_df2}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-29")],
+            "D": [1],
+            "B": [5],
+            "C": [7],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_empty_offset_df():

Review Comment:
   **Suggestion:** Add an explicit return type annotation to this test function to align with the type-hint requirement. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This newly added test function lacks a return type annotation, so the type-hint rule applies here.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b8675998182b417fa3567c762b8750f8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b8675998182b417fa3567c762b8750f8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_time_shifts.py
   **Line:** 416:416
   **Comment:**
   	*Custom Rule: Add an explicit return type annotation to this test function to align with the type-hint requirement.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=f75b1a7a29cd512d693b0931ee3c2a1995ffdca41a7cb89033485d3f3b864c1e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=f75b1a7a29cd512d693b0931ee3c2a1995ffdca41a7cb89033485d3f3b864c1e&reaction=dislike'>👎</a>



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -360,27 +558,38 @@ def test_join_offset_dfs_allows_non_temporal_join_without_time_grain():
     assert "metric__1 year ago" in result.columns
 
 
-def test_join_offset_dfs_raises_when_temporal_key_not_first():
-    """Temporal join key detection works even when it's not the first key."""
+def test_join_offset_dfs_no_time_grain_temporal_key_not_first():

Review Comment:
   **Suggestion:** Add an explicit return type annotation to this new test function to comply with the rule requiring type hints. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is another new Python test function without any type annotation, which is a direct match for the required typing standard.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d73c217821bf407ba1c35b8d0c5a7093&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d73c217821bf407ba1c35b8d0c5a7093&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_time_shifts.py
   **Line:** 561:561
   **Comment:**
   	*Custom Rule: Add an explicit return type annotation to this new test function to comply with the rule requiring type hints.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=136cf16c29633e68b28b142e547795b7936848505c6a40cd3d5a0d89ef33c68b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=136cf16c29633e68b28b142e547795b7936848505c6a40cd3d5a0d89ef33c68b&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4986100216

   CI is green after the master update. One note on the Codecov patch-coverage number: it understates this PR because of a pre-existing quirk in `superset-python-unittest.yml` — the "100% coverage" gate steps re-run pytest with scoped `--cov` targets after the full unit suite, overwriting the coverage data file before the Codecov upload, so unit-test coverage of files like `superset/models/helpers.py` never reaches Codecov. The changed lines here are covered directly by the unit tests added in this PR (`tests/unit_tests/common/test_time_shifts.py`, `tests/unit_tests/utils/date_parser_tests.py`).
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3583076664


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +563,18 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_normalize_time_delta() -> None:
+    assert normalize_time_delta("1 year ago") == {"years": -1}
+    assert normalize_time_delta("2 months later") == {"months": 2}
+    assert normalize_time_delta("28 days ago") == {"days": -28}
+    # quarters are converted to months (pd.DateOffset has no quarters argument)
+    assert normalize_time_delta("1 quarter ago") == {"months": -3}
+    assert normalize_time_delta("2 quarters later") == {"months": 6}

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Incomplete time unit coverage</b></div>
   <div id="fix">
   
   The test only covers 4 time units (year, month, day, quarter) but the implementation supports 8 units. Missing coverage for seconds, minutes, hours, and weeks could allow regressions in those paths to go undetected.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #52d6f6</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4974545703

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3590990561


##########
superset/utils/date_parser.py:
##########
@@ -98,6 +98,9 @@ def normalize_time_delta(human_readable: str) -> dict[str, int]:
     key = matched[2] + "s"
     value = int(matched[1])
     value = -value if matched[3] == "ago" else value
+    if key == "quarters":
+        # pd.DateOffset does not accept a `quarters` argument
+        key, value = "months", value * 3

Review Comment:
   **Suggestion:** The quarter-conversion check is case-sensitive, but the regex match is case-insensitive and preserves the user's original casing. Inputs like `1 Quarter ago` or `1 QUARTER ago` will skip this branch, return `{"Quarters": -1}`, and later fail when passed to `DateOffset`. Normalize the unit key to lowercase before this comparison so quarter offsets work regardless of input case. [incorrect condition logic]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Quarter-offset charts can crash during join-column generation.
   - ⚠️ Grain-less offset alignment silently ignores quarter normalization failures.
   - ⚠️ Time comparison features unreliable for mixed-case quarter inputs.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Configure a timeseries chart using time comparison so the frontend sends a quarter
   offset string like "1 QUARTER ago" in `time_offsets` (see
   `superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/buildQuery.ts:81-99`, which
   flows `formData.time_compare` into `time_offsets`).
   
   2. The backend builds offset queries and then calls `ExploreMixin.join_offset_dfs` from
   `superset/models/helpers.py:2115-2122`, passing the main DataFrame, `offset_dfs`, the
   `time_grain`, and the join keys.
   
   3. Inside `join_offset_dfs` (`superset/models/helpers.py:2434-2480`), for each `offset`
   string (e.g. "1 QUARTER ago") it delegates to `_determine_join_keys`, which for relative
   offsets without a custom producer eventually calls `add_offset_join_column`, and that
   applies `generate_join_column` per row (`superset/models/helpers.py:2525-2580`).
   
   4. In `generate_join_column` (`superset/models/helpers.py:2571-2581`), when `time_offset`
   is "1 QUARTER ago" and the value is datetime-like, the code executes `value = value +
   DateOffset(**normalize_time_delta(time_offset))` without a try/except;
   `normalize_time_delta` at `superset/utils/date_parser.py:53-65` matches the regex
   case-insensitively, sets `key = matched[2] + "s"` yielding "QUARTERs", the `if key ==
   "quarters"` check fails because it is case-sensitive, and the function returns
   `{"QUARTERs": -1}`. Passing this dict to `DateOffset(**...)` raises a
   `ValueError`/`TypeError` ("unexpected keyword argument 'QUARTERs'"), which is not caught
   here and bubbles up, causing the query to fail instead of producing a valid
   quarter-shifted comparison series.
   ```
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4f4db86cb09d4f1faf8494a111b6126a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=4f4db86cb09d4f1faf8494a111b6126a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/utils/date_parser.py
   **Line:** 101:103
   **Comment:**
   	*Incorrect Condition Logic: The quarter-conversion check is case-sensitive, but the regex match is case-insensitive and preserves the user's original casing. Inputs like `1 Quarter ago` or `1 QUARTER ago` will skip this branch, return `{"Quarters": -1}`, and later fail when passed to `DateOffset`. Normalize the unit key to lowercase before this comparison so quarter offsets work regardless of input case.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=5f901d5e3997ef66b0bc9eb8dca8d7fbc237200454cd5789bb8c263fdbda48f0&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=5f901d5e3997ef66b0bc9eb8dca8d7fbc237200454cd5789bb8c263fdbda48f0&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3591549925


##########
superset/utils/date_parser.py:
##########
@@ -120,7 +128,11 @@
     source_dttm = dttm_from_timetuple(
         source_time.timetuple() if source_time else datetime.now().timetuple()
     )
-    return dttm_from_timetuple(cal.parse(human_readable or "", source_dttm)[0])
+    human_readable = _QUARTERS_PATTERN.sub(
+        lambda match: f"{int(match[1]) * 3} months",
+        human_readable or "",

Review Comment:
   ## CodeQL / Polynomial regular expression used on uncontrolled data
   
   This [regular expression](1) that depends on a [user-provided value](2) may run slow on strings with many repetitions of '0'.
   
   [Show more details](https://github.com/apache/superset/security/code-scanning/2583)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3598284673


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]

Review Comment:
   Not changed: `sources`, `deltas`, and `anchored` are locals whose types are fully inferred from their right-hand sides (`list[datetime]`, `set[timedelta]`), so mypy already checks them and an inline annotation would only restate the literal. The file follows this convention — 206 unannotated locals vs 5 annotated, and those 5 are bare declarations before conditional assignment, where inference genuinely is not possible. Happy to annotate if you consider these relevant new variables under the rule.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]
+
+    deltas = {get_past_or_future("1 week ago", src) - src for src in sources}
+    assert deltas == {timedelta(days=-7)}

Review Comment:
   Not changed: `sources`, `deltas`, and `anchored` are locals whose types are fully inferred from their right-hand sides (`list[datetime]`, `set[timedelta]`), so mypy already checks them and an inline annotation would only restate the literal. The file follows this convention — 206 unannotated locals vs 5 annotated, and those 5 are bare declarations before conditional assignment, where inference genuinely is not possible. Happy to annotate if you consider these relevant new variables under the rule.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]
+
+    deltas = {get_past_or_future("1 week ago", src) - src for src in sources}
+    assert deltas == {timedelta(days=-7)}
+
+    anchored = {get_past_or_future("yesterday", src) - src for src in sources}
+    assert len(anchored) > 1

Review Comment:
   Not changed: `sources`, `deltas`, and `anchored` are locals whose types are fully inferred from their right-hand sides (`list[datetime]`, `set[timedelta]`), so mypy already checks them and an inline annotation would only restate the literal. The file follows this convention — 206 unannotated locals vs 5 annotated, and those 5 are bare declarations before conditional assignment, where inference genuinely is not possible. Happy to annotate if you consider these relevant new variables under the rule.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3590948084


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +563,18 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_normalize_time_delta() -> None:
+    assert normalize_time_delta("1 year ago") == {"years": -1}
+    assert normalize_time_delta("2 months later") == {"months": 2}
+    assert normalize_time_delta("28 days ago") == {"days": -28}
+    # quarters are converted to months (pd.DateOffset has no quarters argument)
+    assert normalize_time_delta("1 quarter ago") == {"months": -3}
+    assert normalize_time_delta("2 quarters later") == {"months": 6}

Review Comment:
   <!-- Bito Reply -->
   The suggestion provided by the reviewer was appropriate and helpful. It correctly identified a gap in test coverage for time units (seconds, minutes, hours, and weeks) that were supported by the implementation but missing from the test suite. Addressing this suggestion improves the robustness of the code by ensuring these paths are covered against future regressions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4985873441

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/42054?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `14.28571%` with `24 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 64.43%. Comparing base ([`d68e84e`](https://app.codecov.io/gh/apache/superset/commit/d68e84e7315049325a47270777d35adaeb32b6bb?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`6d5373d`](https://app.codecov.io/gh/apache/superset/commit/6d5373d7d1a987c5ee64d6a9980117e6ba9af660?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 29 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/42054?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/models/helpers.py](https://app.codecov.io/gh/apache/superset/pull/42054?src=pr&el=tree&filepath=superset%2Fmodels%2Fhelpers.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbW9kZWxzL2hlbHBlcnMucHk=) | 8.33% | [21 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/42054?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/utils/date\_parser.py](https://app.codecov.io/gh/apache/superset/pull/42054?src=pr&el=tree&filepath=superset%2Futils%2Fdate_parser.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdXRpbHMvZGF0ZV9wYXJzZXIucHk=) | 50.00% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/42054?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #42054      +/-   ##
   ==========================================
   - Coverage   64.49%   64.43%   -0.06%     
   ==========================================
     Files        2747     2747              
     Lines      153843   153929      +86     
     Branches    35268    35287      +19     
   ==========================================
   - Hits        99221    99186      -35     
   - Misses      52712    52821     +109     
   - Partials     1910     1922      +12     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/42054/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/42054/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.02% <3.57%> (-0.04%)` | :arrow_down: |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/42054/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.83% <14.28%> (-0.06%)` | :arrow_down: |
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/42054/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.89% <14.28%> (-0.06%)` | :arrow_down: |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/42054/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.00% <3.57%> (-0.04%)` | :arrow_down: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/42054/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `58.06% <14.28%> (-0.10%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/42054/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/42054?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3593050167


##########
superset/models/helpers.py:
##########
@@ -1912,6 +1913,19 @@ def processing_time_offsets(  # pylint: disable=too-many-locals,too-many-stateme
                             outer_from_dttm,
                             outer_to_dttm,
                         )
+                    elif parse_human_timedelta(offset, outer_from_dttm) == timedelta():
+                        # get_past_or_future silently returns the source time
+                        # for offsets it cannot parse; querying with an
+                        # unshifted window would present the current period's
+                        # data as the comparison series.
+                        raise QueryObjectValidationError(
+                            _(
+                                "Unable to interpret the time offset: "
+                                "%(offset)s. Use a relative time such as "
+                                '"1 month ago".',
+                                offset=offset,
+                            )
+                        )

Review Comment:
   Valid finding — fixed in 453965c813: the guard (and the grain-less alignment probe, which had the same conflation) checks parsedatetime's parse flag via a new `is_parseable_human_timedelta` instead of comparing the delta to zero, so `0 days ago` renders a self-comparison; regression tests added.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3590974550


##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():

Review Comment:
   Added `-> None` return annotations in aebbacc2a9 — to all 10 new test functions in this file, not just the flagged ones.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls():

Review Comment:
   Added `-> None` return annotations in aebbacc2a9 — to all 10 new test functions in this file, not just the flagged ones.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls():
+    """
+    Without a time grain, offset timestamps that have no exact shifted
+    counterpart in the main series produce nulls instead of raising.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-06-15")], "B": [5]})
+    offset_dfs = {"1 year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_multiple_offsets():

Review Comment:
   Added `-> None` return annotations in aebbacc2a9 — to all 10 new test functions in this file, not just the flagged ones.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,18 +335,215 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset():
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls():
+    """
+    Without a time grain, offset timestamps that have no exact shifted
+    counterpart in the main series produce nulls instead of raising.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-06-15")], "B": [5]})
+    offset_dfs = {"1 year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_multiple_offsets():
+    """
+    Multiple relative offsets without a time grain each align on their own
+    shifted timestamps, and no synthetic join columns leak into the result.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-29")], "D": [1]})
+    offset_df1 = DataFrame({"ds": [Timestamp("2021-01-01")], "B": [5]})
+    offset_df2 = DataFrame({"ds": [Timestamp("2020-01-29")], "C": [7]})
+    offset_dfs = {"28 days ago": offset_df1, "1 year ago": offset_df2}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-29")],
+            "D": [1],
+            "B": [5],
+            "C": [7],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_empty_offset_df():

Review Comment:
   Added `-> None` return annotations in aebbacc2a9 — to all 10 new test functions in this file, not just the flagged ones.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -360,27 +558,38 @@ def test_join_offset_dfs_allows_non_temporal_join_without_time_grain():
     assert "metric__1 year ago" in result.columns
 
 
-def test_join_offset_dfs_raises_when_temporal_key_not_first():
-    """Temporal join key detection works even when it's not the first key."""
+def test_join_offset_dfs_no_time_grain_temporal_key_not_first():

Review Comment:
   Added `-> None` return annotations in aebbacc2a9 — to all 10 new test functions in this file, not just the flagged ones.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4994277530

   🎪 [Showtime](https://github.com/mistercrunch/superset-showtime) is building environment on [GHA](https://github.com/apache/superset/actions/runs/29515927554) for [453965c](https://github.com/apache/superset/commit/453965c)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3598262049


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]
+
+    deltas = {get_past_or_future("1 week ago", src) - src for src in sources}
+    assert deltas == {timedelta(days=-7)}

Review Comment:
   **Suggestion:** Add an explicit type annotation to this newly added computed variable so its set element type is clear to static analyzers. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   The new set-valued variable is inferred by Python but can be explicitly annotated. Since the rule requires type hints on relevant new variables that can be annotated, this omission is a real violation.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ac8927a4a19d408bb627dc5dd26bac1a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ac8927a4a19d408bb627dc5dd26bac1a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/utils/date_parser_tests.py
   **Line:** 645:646
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to this newly added computed variable so its set element type is clear to static analyzers.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=6bc3c9fc63b2038fb327788ccaed79e63e57aab99661b19b419b78c8318e58fa&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=6bc3c9fc63b2038fb327788ccaed79e63e57aab99661b19b419b78c8318e58fa&reaction=dislike'>👎</a>



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]
+
+    deltas = {get_past_or_future("1 week ago", src) - src for src in sources}
+    assert deltas == {timedelta(days=-7)}
+
+    anchored = {get_past_or_future("yesterday", src) - src for src in sources}
+    assert len(anchored) > 1

Review Comment:
   **Suggestion:** Add an explicit type annotation to this newly introduced variable to make the inferred set type explicit and rule-compliant. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is another newly introduced local variable with an inferable set type that could be annotated explicitly. The absence of a type hint violates the Python type-hint rule.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5a35b9783bcb458c95a1e84f0fb369a9&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5a35b9783bcb458c95a1e84f0fb369a9&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/utils/date_parser_tests.py
   **Line:** 648:649
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to this newly introduced variable to make the inferred set type explicit and rule-compliant.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=ba5a9bc3d499cdb4e8cc249be81c40d1ad531f6f793cb79ca55300964340f288&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=ba5a9bc3d499cdb4e8cc249be81c40d1ad531f6f793cb79ca55300964340f288&reaction=dislike'>👎</a>



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]

Review Comment:
   **Suggestion:** Add an explicit type annotation to this collection variable to satisfy the type-hint requirement for relevant new variables. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is a newly added local variable in Python test code, and it lacks an explicit type hint even though its list element type is clearly annotatable. This matches the type-hint rule for relevant variables.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ec6091267d454c0d8e66d983851461a0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ec6091267d454c0d8e66d983851461a0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/utils/date_parser_tests.py
   **Line:** 638:643
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to this collection variable to satisfy the type-hint requirement for relevant new variables.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=63fd2d51318ff704568b1c95bdba0fdad4f47674d2dd0edc7ad882ca09999b74&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=63fd2d51318ff704568b1c95bdba0fdad4f47674d2dd0edc7ad882ca09999b74&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4995708069

   🎪 [Showtime](https://github.com/mistercrunch/superset-showtime) is building environment on [GHA](https://github.com/apache/superset/actions/runs/29527396872) for [41eaa74](https://github.com/apache/superset/commit/41eaa74)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4995823450

   🎪 [Showtime](https://github.com/mistercrunch/superset-showtime) is building environment on [GHA](https://github.com/apache/superset/actions/runs/29528332420) for [47b829d](https://github.com/apache/superset/commit/47b829d)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #42054:
URL: https://github.com/apache/superset/pull/42054


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4985721614

   The `pre-commit (current)` failure is also unrelated to this PR — it's a master breakage: `superset/semantic_layers/mapper.py` defines `_get_time_axis_column` twice (mypy `no-redef`, plus the duplicated tests), from overlapping semantic-layers merges. This PR doesn't touch those files. Upstream fix pending in #42093; once it (and #42080 for the unit-tests failure) lands, I'll update this branch to re-run CI.
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3592968182


##########
superset/utils/date_parser.py:
##########
@@ -66,6 +66,14 @@
     "1st": 1,
 }
 
+# parsedatetime does not understand "N quarters" (it leaves the source time
+# unchanged), so such phrases are rewritten to the equivalent number of months
+# before parsing. The lookbehind and the bounded repetition keep matching
+# linear on user-provided strings (every suffix of an unbounded digit run
+# would be re-scanned) and keep the int() conversion small; longer digit
+# runs fall through to parsedatetime like any other unparseable phrase.
+_QUARTERS_PATTERN = re.compile(r"(?<![0-9])([0-9]{1,10})\s+quarters?\b", re.IGNORECASE)

Review Comment:
   **Suggestion:** Add an explicit type annotation to the compiled regex constant to satisfy the type-hint requirement for new module-level variables. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   The new module-level variable `_QUARTERS_PATTERN` is introduced without an explicit type annotation, which matches the Python type-hint rule for newly added annotatable variables.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=02ae137f27724bb08d0b16e919d24afd&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=02ae137f27724bb08d0b16e919d24afd&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/utils/date_parser.py
   **Line:** 75:75
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to the compiled regex constant to satisfy the type-hint requirement for new module-level variables.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=7c3d8b4be76e05989f7683a89a162e15fdbdc4ea189d554cf89edd1a18ba064b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=7c3d8b4be76e05989f7683a89a162e15fdbdc4ea189d554cf89edd1a18ba064b&reaction=dislike'>👎</a>



##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -1024,6 +1024,159 @@ def fake_query(dct: dict[str, Any]) -> MagicMock:
     assert "2025-06-01" in val, f"Expected shifted-to-dttm in val, got: {val!r}"
 
 
+def test_processing_time_offsets_quarter_offset_shifts_query_window(processor):

Review Comment:
   **Suggestion:** Add explicit type hints to this test function signature, including annotating `processor` and the return type. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is a newly added Python test function in the final file state, and it omits both the `processor` parameter type and a return type annotation. That matches the type-hint rule violation.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=61d009bb539643a3a75df205b4e476fb&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=61d009bb539643a3a75df205b4e476fb&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_query_context_processor.py
   **Line:** 1027:1027
   **Comment:**
   	*Custom Rule: Add explicit type hints to this test function signature, including annotating `processor` and the return type.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=2795ef898d3983f90ac55b11053e5e118ba4fe42477aaf1016c6b6c22a8b7e7d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=2795ef898d3983f90ac55b11053e5e118ba4fe42477aaf1016c6b6c22a8b7e7d&reaction=dislike'>👎</a>



##########
tests/unit_tests/common/test_time_shifts.py:
##########
@@ -334,19 +337,259 @@ def test_join_offset_dfs_totals_query_no_dimensions():
     assert_frame_equal(expected, result)
 
 
-def test_join_offset_dfs_raises_without_time_grain():
-    """Time comparison with relative offsets requires a time grain."""
+def test_join_offset_dfs_no_time_grain_aligns_relative_offset() -> None:
+    """
+    Without a time grain, a relative offset joins on the exact shifted
+    timestamps instead of raising, so saved charts without a grain render
+    with a correctly aligned comparison series.
+    """
+    df = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+        }
+    )
+    offset_df = DataFrame(
+        {
+            "ds": [Timestamp("2020-01-01"), Timestamp("2020-02-01")],
+            "B": [5, 6],
+        }
+    )
+    offset_dfs = {"1 year ago": offset_df}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-01"), Timestamp("2021-02-01")],
+            "D": [1, 2],
+            "B": [5, 6],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_unmatched_timestamps_yield_nulls() -> None:
+    """
+    Without a time grain, offset timestamps that have no exact shifted
+    counterpart in the main series produce nulls instead of raising.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-06-15")], "B": [5]})
+    offset_dfs = {"1 year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_multiple_offsets() -> None:
+    """
+    Multiple relative offsets without a time grain each align on their own
+    shifted timestamps, and no synthetic join columns leak into the result.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-29")], "D": [1]})
+    offset_df1 = DataFrame({"ds": [Timestamp("2021-01-01")], "B": [5]})
+    offset_df2 = DataFrame({"ds": [Timestamp("2020-01-29")], "C": [7]})
+    offset_dfs = {"28 days ago": offset_df1, "1 year ago": offset_df2}
+
+    expected = DataFrame(
+        {
+            "ds": [Timestamp("2021-01-29")],
+            "D": [1],
+            "B": [5],
+            "C": [7],
+        }
+    )
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_empty_offset_df() -> None:
+    """
+    An empty offset series materializes its join keys as NaN floats; the
+    grain-less join must not crash on the dtype mismatch.
+    """
     df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
-    offset_df = DataFrame({"ds": [Timestamp("2021-02-01")], "B": [5]})
+    offset_df = DataFrame({"ds": [float("nan")], "B": [float("nan")]})
     offset_dfs = {"1 year ago": offset_df}
 
-    with pytest.raises(
-        QueryObjectValidationError, match="Time Grain must be specified"
-    ):
-        query_context_processor.join_offset_dfs(
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_quarter_offset() -> None:
+    """
+    Quarter offsets align without a time grain (normalize_time_delta converts
+    quarters to months, since pd.DateOffset has no quarters argument).
+    """
+    df = DataFrame({"ds": [Timestamp("2021-04-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2021-01-01")], "B": [5]})
+    offset_dfs = {"1 quarter ago": offset_df}
+
+    expected = DataFrame({"ds": [Timestamp("2021-04-01")], "D": [1], "B": [5]})
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_free_form_offset() -> None:
+    """
+    Offsets outside the normalize_time_delta grammar (e.g. "one year ago")
+    are aligned with the same parser that shifted the offset query's range.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-01-01")], "B": [5]})
+    offset_dfs = {"one year ago": offset_df}
+
+    expected = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1], "B": [5]})
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert_frame_equal(expected, result)
+
+
+def test_join_offset_dfs_no_time_grain_free_form_offset_tz_microseconds() -> None:
+    """
+    Free-form offsets align timezone-aware, sub-second timestamps: each row's
+    shift is computed from a naive second-truncated copy and applied to the
+    original value, so the join keys keep their timezone and precision.
+    """
+    df = DataFrame(
+        {"ds": [Timestamp("2021-03-04 05:06:07.890123", tz="UTC")], "D": [1]}
+    )
+    offset_df = DataFrame(
+        {"ds": [Timestamp("2020-03-04 05:06:07.890123", tz="UTC")], "B": [5]}
+    )
+    offset_dfs = {"one year ago": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert result["B"].tolist() == [5]
+
+
+def test_join_offset_dfs_no_time_grain_uninterpretable_offset() -> None:
+    """
+    An offset that no parser can interpret falls back to joining on the raw
+    keys (an empty comparison series) instead of crashing.
+    """
+    df = DataFrame({"ds": [Timestamp("2021-01-01")], "D": [1]})
+    offset_df = DataFrame({"ds": [Timestamp("2020-01-01")], "B": [5]})
+    offset_dfs = {"not a real offset": offset_df}
+
+    result = query_context_processor.join_offset_dfs(
+        df, offset_dfs, time_grain=None, join_keys=["ds"]
+    )
+
+    assert "B" in result.columns
+    assert result["B"].isna().all()
+
+
+def test_join_offset_dfs_no_time_grain_uninterpretable_offset_subsecond(
+    caplog,
+) -> None:

Review Comment:
   **Suggestion:** Add a concrete type annotation for the `caplog` test fixture parameter in this new test function signature. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This new test function introduces an untyped parameter (`caplog`) even though it can be annotated, which violates the repository rule requiring Python type hints on new or modified code.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=43e17b854c4248ac9076613e8982488b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=43e17b854c4248ac9076613e8982488b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_time_shifts.py
   **Line:** 509:511
   **Comment:**
   	*Custom Rule: Add a concrete type annotation for the `caplog` test fixture parameter in this new test function signature.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=3a8e81a29cf948961325c15ff7015dd9e38f7c68f0a130aff76b756c5addcf91&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=3a8e81a29cf948961325c15ff7015dd9e38f7c68f0a130aff76b756c5addcf91&reaction=dislike'>👎</a>



##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -1024,6 +1024,159 @@ def fake_query(dct: dict[str, Any]) -> MagicMock:
     assert "2025-06-01" in val, f"Expected shifted-to-dttm in val, got: {val!r}"
 
 
+def test_processing_time_offsets_quarter_offset_shifts_query_window(processor):
+    """A quarter offset must shift the offset query's window, not just the
+    join keys. parsedatetime does not understand "1 quarter ago", so without
+    rewriting quarters to months the offset subquery silently runs against
+    the current period and the comparison series joins to nulls. The fake
+    query below derives its rows from the requested window, so the join only
+    yields the expected values when the window was actually shifted.
+    """
+    from superset.common.query_object import QueryObject
+    from superset.models.helpers import ExploreMixin
+
+    for method in (
+        "processing_time_offsets",
+        "_align_offset_without_time_grain",
+        "_coalesce_offset_index",
+    ):
+        setattr(
+            processor._qc_datasource,
+            method,
+            getattr(ExploreMixin, method).__get__(processor._qc_datasource),
+        )
+
+    df = pd.DataFrame(
+        {
+            "__timestamp": pd.to_datetime(["2024-04-01", "2024-05-01", "2024-06-01"]),
+            "sum__num": [100, 200, 300],
+        }
+    )
+
+    query_object = QueryObject(
+        datasource=MagicMock(),
+        granularity="ds",
+        columns=[],
+        metrics=["sum__num"],
+        is_timeseries=True,
+        time_offsets=["1 quarter ago"],
+        filters=[
+            {
+                "col": "ds",
+                "op": "TEMPORAL_RANGE",
+                "val": "2024-04-01 : 2024-07-01",
+            }
+        ],
+    )
+
+    captured: list[dict[str, Any]] = []
+
+    def fake_query(dct: dict[str, Any]) -> MagicMock:
+        captured.append(dct)
+        result = MagicMock()
+        result.df = pd.DataFrame(
+            {
+                "__timestamp": pd.date_range(
+                    start=dct["from_dttm"], periods=3, freq="MS"
+                ),
+                "sum__num": [1.0, 2.0, 3.0],
+            }
+        )
+        result.query = "SELECT 1"
+        return result
+
+    processor._qc_datasource.query = fake_query
+    processor._qc_datasource.normalize_df = MagicMock(
+        side_effect=lambda offset_df, _query_object: offset_df
+    )
+
+    with (
+        patch(
+            "superset.models.helpers.get_since_until_from_query_object",
+            return_value=(pd.Timestamp("2024-04-01"), pd.Timestamp("2024-07-01")),
+        ),
+        patch(
+            "superset.common.utils.query_cache_manager.QueryCacheManager"
+        ) as mock_cache_manager,
+        patch.object(
+            processor._qc_datasource,
+            "get_time_grain",
+            return_value=None,
+        ),
+    ):
+        mock_cache = MagicMock()
+        mock_cache.is_loaded = False
+        mock_cache_manager.get.return_value = mock_cache
+
+        result = processor._qc_datasource.processing_time_offsets(
+            df, query_object, None, None, False
+        )
+
+    assert len(captured) == 1
+    assert captured[0]["from_dttm"] == pd.Timestamp("2024-01-01")
+    assert captured[0]["to_dttm"] == pd.Timestamp("2024-04-01")
+    assert result["df"]["sum__num__1 quarter ago"].tolist() == [1.0, 2.0, 3.0]
+
+
+def test_processing_time_offsets_rejects_unparseable_offset(processor):

Review Comment:
   **Suggestion:** Add explicit type hints to this test function signature, including annotating `processor` and the return type. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This newly added Python test function also omits type annotations for its parameter and return value, so the custom type-hint rule is violated here as well.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7a4cddd5f1194d909f09d2507c17188a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=7a4cddd5f1194d909f09d2507c17188a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/common/test_query_context_processor.py
   **Line:** 1121:1121
   **Comment:**
   	*Custom Rule: Add explicit type hints to this test function signature, including annotating `processor` and the return type.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=2b82bb74fb5e69195395bdeb60a5cfaa42e6b979d13d2070266b4b7adffb5155&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=2b82bb74fb5e69195395bdeb60a5cfaa42e6b979d13d2070266b4b7adffb5155&reaction=dislike'>👎</a>



##########
superset/models/helpers.py:
##########
@@ -2369,31 +2483,13 @@ def join_offset_dfs(
             time range instead of being truncated to the main series' range. This
             uses an outer join so offset-only rows (e.g. the rest of a prior day when
             the current day is still in progress) are preserved.
+        :param x_axis_label: The query's temporal x-axis label, used to pick the
+            temporal join key when no time grain is set.
         """
         join_column_producer = app.config["TIME_GRAIN_JOIN_COLUMN_PRODUCERS"].get(
             time_grain
         )
-
-        if not time_grain:
-            has_temporal_join_key = any(
-                pd.api.types.is_datetime64_any_dtype(df[key])
-                for key in join_keys
-                if key in df.columns
-            )
-            if has_temporal_join_key:
-                has_relative_offset = any(
-                    not (
-                        self.is_valid_date_range(offset)
-                        and feature_flag_manager.is_feature_enabled(
-                            "DATE_RANGE_TIMESHIFTS_ENABLED"
-                        )
-                    )
-                    for offset in offset_dfs
-                )
-                if has_relative_offset:
-                    raise QueryObjectValidationError(
-                        _("Time Grain must be specified when using Time Comparison.")
-                    )
+        original_columns = list(df.columns)

Review Comment:
   **Suggestion:** Add an explicit type annotation for this new local variable to satisfy the strict type-hinting requirement for relevant variables. [custom_rule]
   
   **Severity Level:** Minor 🧹
   <details>
   <summary><b>Why it matters? ⭐ </b></summary>
   
   This is a newly added local variable in Python code and its type is inferable as a list of column names, so it can be annotated under the type-hinting rule. The existing code omits that annotation, matching the reported violation.
   </details>
   <details>
   <summary><b>Rule source 📖 </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f32075426273469e9e2cf1669519ee4f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f32075426273469e9e2cf1669519ee4f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/models/helpers.py
   **Line:** 2492:2492
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this new local variable to satisfy the strict type-hinting requirement for relevant variables.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=e4b3ddbab14d248f5ef3aa01cfdf3f7db385ccc17b3f945919708b88d1a45aef&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42054&comment_hash=e4b3ddbab14d248f5ef3aa01cfdf3f7db385ccc17b3f945919708b88d1a45aef&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3598337819


##########
superset/models/helpers.py:
##########
@@ -2312,8 +2349,110 @@ def _determine_join_keys(
             return self._process_date_range_offset(offset_df, join_keys)
 
         else:
+            return self._align_offset_without_time_grain(
+                df, offset_df, offset, join_keys, x_axis_label
+            )
+
+    def _align_offset_without_time_grain(
+        self,
+        df: pd.DataFrame,
+        offset_df: pd.DataFrame,
+        offset: str,
+        join_keys: list[str],
+        x_axis_label: str | None = None,
+    ) -> tuple[pd.DataFrame, list[str]]:
+        """
+        Determine join keys for a relative offset when no time grain is set.
+
+        Without a time grain there is no truncated join column, but the two
+        series can still be aligned exactly: shifting the main series'
+        timestamps by the offset delta lands them on the offset series' raw
+        timestamps (normalize_time_delta returns a negative delta for "... ago"
+        offsets). Timestamps without an exact counterpart in the offset series
+        produce nulls, mirroring the grain-based join, and null timestamps in
+        the two series join to each other (both stringify to "NaT"). When
+        there is no temporal join key the original join keys are used as-is.
+
+        The shift is computed on wall-clock time, with any timezone dropped for
+        the duration of the alignment. The offset query's own time range was
+        shifted the same way -- ``get_past_or_future`` reads naive timestamps
+        -- so the rows it returns carry the source wall clock, and matching on
+        it is what aligns the two series. Re-localizing the result would only
+        reintroduce the DST edge cases that wall-clock arithmetic sidesteps:
+        shifting onto a skipped or repeated local hour raises out of pandas.
+        Both sides are normalized identically, so the two readings of a
+        repeated hour still align with each other.
+
+        Month, quarter, and year offsets shift via ``DateOffset``, which clamps
+        to a valid calendar day (e.g. Mar 29, 30, and 31 all shift back one
+        month to Feb 28), so on daily/irregular data several end-of-month rows
+        can align to the same offset timestamp. This mirrors the inherent
+        ambiguity of "the same day N months ago" without a time grain to
+        truncate against.
+        """
+        # Prefer the query's temporal x-axis when it is a join key; otherwise
+        # use the first datetime join key.
+        candidate_keys = sorted(join_keys, key=lambda key: key != x_axis_label)
+        temporal_join_key = next(
+            (
+                key
+                for key in candidate_keys
+                if key in df.columns
+                and key in offset_df.columns
+                and pd.api.types.is_datetime64_any_dtype(df[key])

Review Comment:
   Not changed — the suggested fix would introduce the very failure it describes, and I could not find a reachable case for the original one.
   
   Swapping in `is_datetime_series` makes the guard accept object-dtype dates, but everything downstream still assumes `datetime64`, and the two sides are treated asymmetrically: `df` gets shifted, `offset_df` is only stringified. With an object-backed date axis on both sides (the realistic case — same driver, same query shape), verified on pandas 2.2.3:
   
   ```
   df side (shifted) : ['2021-01-01 00:00:00', '2021-01-02 00:00:00']   # date + DateOffset -> Timestamp
   offset side (raw) : ['2021-01-01', '2021-01-02']                     # str(datetime.date)
   -> zero overlap -> empty comparison
   ```
   
   The free-form branch fares worse: `shift()` calls `value.floor("s")`, and `datetime.date` has no `.floor` — `AttributeError` instead of a fallback. Correctly supporting object-backed axes means coercing *both* sides with `pd.to_datetime` before the shift, not broadening detection.
   
   On reachability: `processing_time_offsets` runs on the output of `normalize_df`, which sends every `is_dttm` base-axis label through `normalize_dttm_col` -> `_process_datetime_column` -> `pd.to_datetime`, so the temporal x-axis arrives as `datetime64`. The guard also matches the existing convention in the same dispatch function — the grain-based branch has used `is_datetime64_any_dtype` since a2722532438. `is_datetime_series` is used at helpers.py:2011 to ask a different question (is this axis conceptually temporal, for filter rewriting) rather than to gate datetime arithmetic. Where the dtype genuinely is not `datetime64`, falling back to the raw join keys is deliberate and non-fatal.
   
   Happy to add the two-sided `pd.to_datetime` coercion if you have a concrete query that lands an object-dtype temporal column in `processing_time_offsets` after `normalize_df` — that is the piece I could not construct.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3591574078


##########
superset/utils/date_parser.py:
##########
@@ -120,7 +128,11 @@
     source_dttm = dttm_from_timetuple(
         source_time.timetuple() if source_time else datetime.now().timetuple()
     )
-    return dttm_from_timetuple(cal.parse(human_readable or "", source_dttm)[0])
+    human_readable = _QUARTERS_PATTERN.sub(
+        lambda match: f"{int(match[1]) * 3} months",
+        human_readable or "",

Review Comment:
   Fixed in feaf01e6e8: added a negative lookbehind and bounded the digit repetition (`(?<![0-9])([0-9]{1,10})`) so matching stays linear on long digit runs; oversized counts now fall through to parsedatetime as unparseable, with a regression test for a 100k-digit input.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3598288804


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]
+
+    deltas = {get_past_or_future("1 week ago", src) - src for src in sources}
+    assert deltas == {timedelta(days=-7)}

Review Comment:
   The flagged issue is **not really necessary to fix** here.
   
   `sources`, `deltas`, and `anchored` are local variables with fully inferable types from their assignments:
   
   - `sources` → `list[datetime]`
   - `deltas` → `set[timedelta]`
   - `anchored` → `set[timedelta]`
   
   So static analyzers already know their element types, and an explicit annotation would be redundant rather than clarifying.
   
   If you want to make the intent extra explicit, you could annotate `deltas` or `anchored` like this:
   
   ```python
   deltas: set[timedelta] = {get_past_or_future("1 week ago", src) - src for src in sources}
   ```
   
   But I don’t think that’s required for correctness, and the current code is consistent with the surrounding test style.
   
   If you’d like, I can also review the other comments on this PR and suggest any minimal follow-up fixes.



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +565,109 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)
+    assert parse_human_timedelta("not a real offset", dttm) == timedelta(0)
+
+
+def test_is_parseable_human_timedelta() -> None:
+    assert is_parseable_human_timedelta("1 week ago")
+    assert is_parseable_human_timedelta("one year ago")
+    assert is_parseable_human_timedelta("1 quarter ago")
+    # zero-shift phrases parse successfully even though their delta is zero
+    assert is_parseable_human_timedelta("0 days ago")
+    assert not is_parseable_human_timedelta("not a real offset")
+    assert not is_parseable_human_timedelta("invalid-date-range")
+    assert not is_parseable_human_timedelta("")
+    assert not is_parseable_human_timedelta(None)
+    # absurdly long digit runs are not rewritten to months; they are
+    # unparseable like any other unintelligible phrase
+    assert not is_parseable_human_timedelta("9" * 100_000 + " quarters ago")
+
+
+def test_is_constant_human_timedelta() -> None:
+    # phrases that shift every source time by the same amount
+    assert is_constant_human_timedelta("1 week ago")
+    assert is_constant_human_timedelta("one year ago")
+    assert is_constant_human_timedelta("1 quarter ago")
+    assert is_constant_human_timedelta("2 days later")
+    # a zero shift is still a constant one
+    assert is_constant_human_timedelta("0 days ago")
+    # anchors resolve to a fixed point instead: how far they move a source
+    # time depends on where in the day that source time falls
+    assert not is_constant_human_timedelta("yesterday")
+    assert not is_constant_human_timedelta("last month")
+    assert not is_constant_human_timedelta("noon")
+    # a phrase nothing can parse is not a delta either
+    assert not is_constant_human_timedelta("not a real offset")
+    assert not is_constant_human_timedelta("")
+    assert not is_constant_human_timedelta(None)
+
+
+def test_is_constant_human_timedelta_matches_applied_shift() -> None:
+    """
+    The probes stand in for real source timestamps, so the verdict has to hold
+    for source times they never looked at: an accepted phrase shifts arbitrary
+    timestamps equally, a rejected one does not.
+    """
+    sources = [
+        datetime(2021, 3, 14, 2, 30),
+        datetime(2021, 11, 7, 1, 30),
+        datetime(2024, 2, 29, 23, 59, 59),
+        datetime(2020, 1, 1, 0, 0),
+    ]

Review Comment:
   The comment is **not really necessary here**.
   
   `sources`, `deltas`, and `anchored` are all fully inferred from their RHS:
   
   - `sources` → `list[datetime]`
   - `deltas` → `set[timedelta]`
   - `anchored` → `set[timedelta]`
   
   So the type information is already explicit enough for mypy, and adding annotations would mostly be redundant.
   
   If you want to satisfy the rule mechanically, you could write:
   
   ```python
   sources: list[datetime] = [
       datetime(2021, 3, 14, 2, 30),
       datetime(2021, 11, 7, 1, 30),
       datetime(2024, 2, 29, 23, 59, 59),
       datetime(2020, 1, 1, 0, 0),
   ]
   ```
   
   but I don’t think it adds value here. I’d keep the test as-is unless the team wants to enforce annotations on every new local variable consistently.
   
   If you want, I can also review the other comments on this PR and suggest the minimal fixes for those too.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #42054:
URL: https://github.com/apache/superset/pull/42054#discussion_r3593073251


##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +564,70 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for local variables in test files when the type is already obvious from the initializer (for example, `datetime(...)` literals).
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/utils/date_parser.py:
##########
@@ -95,9 +105,12 @@ def normalize_time_delta(human_readable: str) -> dict[str, int]:
     if not matched:
         raise TimeDeltaAmbiguousError(human_readable)
 
-    key = matched[2] + "s"
+    key = matched[2].lower() + "s"

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations on local variables initialized from obvious expressions/literals in Python; reserve this rule for function signatures and module-level names.
   
   **Applied to:**
     - `**/*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/utils/date_parser_tests.py:
##########
@@ -561,6 +564,70 @@ def test_get_past_or_future() -> None:
     assert get_past_or_future("3 month", dttm) == datetime(2020, 5, 29)
 
 
+def test_get_past_or_future_quarters() -> None:
+    # parsedatetime has no notion of quarters (it would leave the source time
+    # unchanged); quarter phrases are rewritten to months before parsing
+    dttm = datetime(2024, 5, 15, 10, 30, 45)
+    assert get_past_or_future("1 quarter ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    assert get_past_or_future("2 quarters ago", dttm) == datetime(
+        2023, 11, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 quarter later", dttm) == datetime(
+        2024, 8, 15, 10, 30, 45
+    )
+    assert get_past_or_future("1 QUARTER ago", dttm) == datetime(
+        2024, 2, 15, 10, 30, 45
+    )
+    # absurdly long digit runs are not rewritten (bounded to keep matching
+    # linear and the month count small); they parse like any other
+    # unintelligible phrase, i.e. the source time comes back unchanged
+    assert get_past_or_future("0" * 100_000 + " quarters ago", dttm) == dttm
+
+
+def test_parse_human_timedelta_unparseable_is_zero() -> None:
+    # the parser leaves unparseable phrases as the source time, so their
+    # delta is zero; a zero delta alone cannot distinguish them from
+    # legitimate zero-shift phrases (see is_parseable_human_timedelta)
+    dttm = datetime(2024, 5, 15)

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations for local variables initialized with `datetime(...)` literals in test files; follow the existing test-file style.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(charts): render time comparison without a time grain [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #42054:
URL: https://github.com/apache/superset/pull/42054#issuecomment-4994440081

   🎪 [Showtime](https://github.com/mistercrunch/superset-showtime) deployed environment on [GHA](https://github.com/apache/superset/actions/runs/29515927554) for [453965c](https://github.com/apache/superset/commit/453965c)
   
   • **Environment:** http://54.202.33.197:8080 (admin/admin)
   • **Lifetime:** 48h auto-cleanup
   • **Updates:** New commits create fresh environments automatically


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org