You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "betodealmeida (via GitHub)" <gi...@apache.org> on 2025/02/11 22:10:40 UTC

[PR] feat: recursive metric definitions [superset]

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

   <!---
   Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
   Example:
   fix(dashboard): load charts correctly
   -->
   
   ### SUMMARY
   <!--- Describe the change below, including rationale and design decisions -->
   
   Allow recursive metric definitions in datasets. See https://github.com/apache/superset/pull/32175 for more context.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   <!--- Skip this if not applicable -->
   
   ### TESTING INSTRUCTIONS
   <!--- Required! What steps can be taken to manually verify the changes? -->
   
   ### ADDITIONAL INFORMATION
   <!--- Check any relevant boxes with "x" -->
   <!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
   - [ ] 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
   


-- 
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] feat: recursive metric definitions [superset]

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


-- 
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] feat: recursive metric definitions [superset]

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

   This is super cool!


-- 
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] feat: recursive metric definitions [superset]

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

   Hey @adamcunnington-mlg We typically do biweekly releases in Preset, so in case we're able to wrap it up in the current sprint we'd be looking at March 5th. Let's move this conversation to our support ticket to make sure we can centralize the conversation and keep the rest of the team up to date 🙌 🙏 


-- 
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] feat: recursive metric definitions [superset]

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


##########
superset/jinja_context.py:
##########
@@ -908,16 +929,32 @@ def metric_macro(metric_key: str, dataset_id: Optional[int] = None) -> str:
     dataset = DatasetDAO.find_by_id(dataset_id)
     if not dataset:
         raise DatasetNotFoundError(f"Dataset ID {dataset_id} not found.")
+
     metrics: dict[str, str] = {
         metric.metric_name: metric.expression for metric in dataset.metrics
     }
-    dataset_name = dataset.table_name
-    if metric := metrics.get(metric_key):
-        return metric
-    raise SupersetTemplateException(
-        _(
-            "Metric ``%(metric_name)s`` not found in %(dataset_name)s.",
-            metric_name=metric_key,
-            dataset_name=dataset_name,
+    if metric_key not in metrics:
+        raise SupersetTemplateException(
+            _(
+                "Metric ``%(metric_name)s`` not found in %(dataset_name)s.",
+                metric_name=metric_key,
+                dataset_name=dataset.table_name,
+            )
         )
-    )
+
+    definition = metrics[metric_key]
+
+    env = SandboxedEnvironment(undefined=DebugUndefined)
+    context = {"metric": partial(safe_proxy, metric_macro)}
+    while has_metric_macro(definition, env):
+        old_definition = definition
+        template = env.from_string(definition)
+        try:
+            definition = template.render(context)
+        except RecursionError as ex:
+            raise SupersetTemplateException("Cyclic metric macro detected") from ex
+
+        if definition == old_definition:
+            break

Review Comment:
   ### Weak cycle detection in metric macro resolution <sub>![category Functionality](https://img.shields.io/badge/Functionality-0284c7)</sub>
   
   <details>
     <summary>Tell me more</summary>
   
   ###### What is the issue?
   The infinite loop prevention logic using definition == old_definition will fail to detect some types of cyclic dependencies where the rendered output doesn't match exactly with the input but still creates a cycle.
   
   ###### Why this matters
   If metric A references metric B which references metric A with slight variations in whitespace or formatting, the current check won't detect the cycle until a RecursionError occurs.
   
   ###### Suggested change ∙ *Feature Preview*
   Implement a visited set to track processed metric names and detect cycles earlier:
   ```python
   def metric_macro(metric_key: str, dataset_id: Optional[int] = None, visited: Optional[set[str]] = None) -> str:
   
       if visited is None:
   
           visited = set()
   
       if metric_key in visited:
   
           raise SupersetTemplateException(f"Cyclic dependency detected for metric {metric_key}")
   
       visited.add(metric_key)
   
       # ... rest of the function
   
   ```
   
   
   </details>
   
   <sub>
   
   [![Report a problem with this comment](https://img.shields.io/badge/Report%20a%20problem%20with%20this%20comment-gray.svg?logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmNWVjMDAiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBjbGFzcz0ibHVjaWRlIGx1Y2lkZS10cmlhbmdsZS1hbGVydCI+PHBhdGggZD0ibTIxLjczIDE4LTgtMTRhMiAyIDAgMCAwLTMuNDggMGwtOCAxNEEyIDIgMCAwIDAgNCAyMWgxNmEyIDIgMCAwIDAgMS43My0zIi8+PHBhdGggZD0iTTEyIDl2NCIvPjxwYXRoIGQ9Ik0xMiAxN2guMDEiLz48L3N2Zz4=)](https://app.korbit.ai/feedback/aa91ff46-6083-4491-9416-b83dd1994b51/a33dd8f8-f111-4253-8c9b-627b5679f11d?suggestedFixEnabled=true)
   
   💬 Chat with Korbit by mentioning @korbit-ai.
   </sub>
   
   <!--- korbi internal id:7632080c-648e-4b9a-8ccc-5dc48d6726c0 -->
   



-- 
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] feat: recursive metric definitions [superset]

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

   Hi @betodealmeida @Vitor-Avila @eschutho we will send a separate note about this but it looks like the requirement was interpreted too explicitly. I'm sorry that we did not give more explicit examples. We are testing today and see that the solution implemented is one that recursively expands only metric references within the recursive expansion.
   
   Rather, we need the jinja to be expanded such that metric references are fully expanded.
   
   E.g. metric a depends on metric b and metric b contains jinja other than just a metric macro that needs to be expanded.
   
   We assumed this would be covered by "recursively expand metric macro" but appreciate how this could be understood too narrowly.
   
   An example of the problem:
   ```
   SAFE_DIVIDE(
     {{ metric("metric_mrt_all_clients__cross_channel__summary__dynamic_kpi_count") }},
     SUM(`engagements`)
   )
   ```
   
   gets expanded to a query like this
   ```
   -- 6dcd92a04feb50f14bbcf07c661680ba
   SELECT SAFE_DIVIDE(
     SUM(0{% for x in filter_values("dynamic_kpi") %}
       {{ " + COALESCE(kpis." + x + "_count, 0)" }}
     {% endfor %}),
     SUM(`engagements`)
   ) AS `metric_mrt_all_clients__cross_channel__summary__dynamic_cvr` 
   FROM `DBT_ANDY`.`CROSS_CHANNEL` ORDER BY `metric_mrt_all_clients__cross_channel__summary__dynamic_cvr` DESC
    LIMIT 1000
   -- 6dcd92a04feb50f14bbcf07c661680ba;
   ```
   
   Here you can see `metric_mrt_all_clients__cross_channel__summary__dynamic_kpi_count`'s expression contained jinja that has not been expanded and so bad syntax gets sent to DB.


-- 
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] feat: recursive metric definitions [superset]

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

   Tested and looks good! Thanks @betodealmeida!


-- 
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] feat: recursive metric definitions [superset]

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

   Ah, I see! I'll fix it. Thanks for the recommendation!


-- 
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] feat: recursive metric definitions [superset]

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

   Based on your review schedule, I'll hold off on reviewing this PR until it's marked as ready for review. If you'd like me to take a look now, comment `/korbit-review`.
   
   > Your admin can change your review schedule in the [Korbit Console](https://app.korbit.ai/settings)
   
   


-- 
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] feat: recursive metric definitions [superset]

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


##########
superset/jinja_context.py:
##########
@@ -908,16 +929,32 @@ def metric_macro(metric_key: str, dataset_id: Optional[int] = None) -> str:
     dataset = DatasetDAO.find_by_id(dataset_id)
     if not dataset:
         raise DatasetNotFoundError(f"Dataset ID {dataset_id} not found.")
+
     metrics: dict[str, str] = {
         metric.metric_name: metric.expression for metric in dataset.metrics
     }
-    dataset_name = dataset.table_name
-    if metric := metrics.get(metric_key):
-        return metric
-    raise SupersetTemplateException(
-        _(
-            "Metric ``%(metric_name)s`` not found in %(dataset_name)s.",
-            metric_name=metric_key,
-            dataset_name=dataset_name,
+    if metric_key not in metrics:
+        raise SupersetTemplateException(
+            _(
+                "Metric ``%(metric_name)s`` not found in %(dataset_name)s.",
+                metric_name=metric_key,
+                dataset_name=dataset.table_name,
+            )
         )
-    )
+
+    definition = metrics[metric_key]
+
+    env = SandboxedEnvironment(undefined=DebugUndefined)

Review Comment:
   @betodealmeida is this SandboxedEnvironment intentional?



-- 
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] feat: recursive metric definitions [superset]

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

   Thanks so much @betodealmeida really appreciate the fast response - not wanting to add any pressure but if you are able to give any sense of ETA, would massively help us manage expectations and the remaining parts of our release plan that relate to our 18 month-long DBT upgrade! Is it likely we'd have to wait until next Thursday for a release? Thank you


-- 
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