bito-code-review[bot] commented on code in PR #38402:
URL: https://github.com/apache/superset/pull/38402#discussion_r2927514294
##########
superset/mcp_service/chart/validation/schema_validator.py:
##########
@@ -282,6 +286,82 @@ def _pre_validate_pie_config(
return True, None
+ @staticmethod
+ def _pre_validate_handlebars_config(
+ config: Dict[str, Any],
+ ) -> Tuple[bool, ChartGenerationError | None]:
+ """Pre-validate handlebars chart configuration."""
+ if "handlebars_template" not in config:
+ return False, ChartGenerationError(
+ error_type="missing_handlebars_template",
+ message="Handlebars chart missing required field:
handlebars_template",
+ details="Handlebars charts require a 'handlebars_template'
string "
+ "containing Handlebars HTML template markup",
+ suggestions=[
+ "Add 'handlebars_template' with a Handlebars HTML
template",
+ "Data is available as {{data}} array in the template",
+ "Example: '<ul>{{#each data}}<li>{{this.name}}: "
+ "{{this.value}}</li>{{/each}}</ul>'",
+ ],
+ error_code="MISSING_HANDLEBARS_TEMPLATE",
+ )
+
+ template = config.get("handlebars_template")
+ if not isinstance(template, str) or not template.strip():
+ return False, ChartGenerationError(
+ error_type="invalid_handlebars_template",
+ message="Handlebars template must be a non-empty string",
+ details="The 'handlebars_template' field must be a non-empty
string "
+ "containing valid Handlebars HTML template markup",
+ suggestions=[
+ "Ensure handlebars_template is a non-empty string",
+ "Example: '<ul>{{#each
data}}<li>{{this.name}}</li>{{/each}}</ul>'",
+ ],
+ error_code="INVALID_HANDLEBARS_TEMPLATE",
+ )
+
+ query_mode = config.get("query_mode", "aggregate")
+ if query_mode not in ("aggregate", "raw"):
+ return False, ChartGenerationError(
+ error_type="invalid_query_mode",
+ message="Invalid query_mode for handlebars chart",
+ details="query_mode must be either 'aggregate' or 'raw'",
+ suggestions=[
+ "Use 'aggregate' for aggregated data (default)",
+ "Use 'raw' for individual rows",
+ ],
+ error_code="INVALID_QUERY_MODE",
+ )
+
+ if query_mode == "raw" and "columns" not in config:
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Validation Logic Inconsistency</b></div>
<div id="fix">
The pre-validation check for columns in raw mode should match the Pydantic
schema behavior. Currently it only fails if 'columns' key is absent, but passes
if columns is present but empty. The schema's model_validator requires not
self.columns (truthy check), so pre-validation should use not
config.get('columns') to catch empty lists too.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
if query_mode == "raw" and not config.get("columns"):
````
</div>
</details>
</div>
<small><i>Code Review Run #d0cdaa</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
##########
superset/mcp_service/chart/validation/schema_validator.py:
##########
@@ -282,6 +286,82 @@ def _pre_validate_pie_config(
return True, None
+ @staticmethod
+ def _pre_validate_handlebars_config(
+ config: Dict[str, Any],
+ ) -> Tuple[bool, ChartGenerationError | None]:
+ """Pre-validate handlebars chart configuration."""
+ if "handlebars_template" not in config:
+ return False, ChartGenerationError(
+ error_type="missing_handlebars_template",
+ message="Handlebars chart missing required field:
handlebars_template",
+ details="Handlebars charts require a 'handlebars_template'
string "
+ "containing Handlebars HTML template markup",
+ suggestions=[
+ "Add 'handlebars_template' with a Handlebars HTML
template",
+ "Data is available as {{data}} array in the template",
+ "Example: '<ul>{{#each data}}<li>{{this.name}}: "
+ "{{this.value}}</li>{{/each}}</ul>'",
+ ],
+ error_code="MISSING_HANDLEBARS_TEMPLATE",
+ )
+
+ template = config.get("handlebars_template")
+ if not isinstance(template, str) or not template.strip():
+ return False, ChartGenerationError(
+ error_type="invalid_handlebars_template",
+ message="Handlebars template must be a non-empty string",
+ details="The 'handlebars_template' field must be a non-empty
string "
+ "containing valid Handlebars HTML template markup",
+ suggestions=[
+ "Ensure handlebars_template is a non-empty string",
+ "Example: '<ul>{{#each
data}}<li>{{this.name}}</li>{{/each}}</ul>'",
+ ],
+ error_code="INVALID_HANDLEBARS_TEMPLATE",
+ )
+
+ query_mode = config.get("query_mode", "aggregate")
+ if query_mode not in ("aggregate", "raw"):
+ return False, ChartGenerationError(
+ error_type="invalid_query_mode",
+ message="Invalid query_mode for handlebars chart",
+ details="query_mode must be either 'aggregate' or 'raw'",
+ suggestions=[
+ "Use 'aggregate' for aggregated data (default)",
+ "Use 'raw' for individual rows",
+ ],
+ error_code="INVALID_QUERY_MODE",
+ )
+
+ if query_mode == "raw" and "columns" not in config:
+ return False, ChartGenerationError(
+ error_type="missing_raw_columns",
+ message="Handlebars chart in 'raw' mode requires 'columns'",
+ details="When query_mode is 'raw', you must specify which
columns "
+ "to include in the query results",
+ suggestions=[
+ "Add 'columns': [{'name': 'column_name'}] for raw mode",
+ "Or use query_mode='aggregate' with 'metrics' "
+ "and optional 'groupby'",
+ ],
+ error_code="MISSING_RAW_COLUMNS",
+ )
+
+ if query_mode == "aggregate" and "metrics" not in config:
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Validation Logic Inconsistency</b></div>
<div id="fix">
Similar to the columns issue, the metrics validation should check for truthy
values to match the schema's model_validator behavior. Empty metrics lists
should be rejected early.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
if query_mode == "aggregate" and not config.get("metrics"):
````
</div>
</details>
</div>
<small><i>Code Review Run #d0cdaa</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
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -662,6 +662,88 @@ class MixedTimeseriesChartConfig(BaseModel):
filters: List[FilterConfig] | None = Field(None, description="Filters to
apply")
+class HandlebarsChartConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ chart_type: Literal["handlebars"] = Field(
+ ...,
+ description=(
+ "Chart type discriminator - MUST be 'handlebars' for custom HTML "
+ "template charts. Handlebars charts render query results using "
+ "Handlebars templates, enabling fully custom layouts like KPI
cards, "
+ "leaderboards, and formatted reports."
+ ),
+ )
+ handlebars_template: str = Field(
+ ...,
+ description=(
+ "Handlebars HTML template string. Data is available as {{data}}
array. "
+ "Built-in helpers: {{dateFormat val format='YYYY-MM-DD'}}, "
+ "{{formatNumber val}}, {{stringify obj}}. "
+ "Example: '<ul>{{#each data}}<li>{{this.name}}:
{{this.value}}</li>"
+ "{{/each}}</ul>'"
+ ),
+ min_length=1,
+ max_length=50000,
+ )
+ query_mode: Literal["aggregate", "raw"] = Field(
+ "aggregate",
+ description=(
+ "Query mode: 'aggregate' groups data with metrics, "
+ "'raw' returns individual rows"
+ ),
+ )
+ columns: list[ColumnRef] | None = Field(
+ None,
+ description=(
+ "Columns to display in raw mode (query_mode='raw'). "
+ "Each column specifies a column name to include in the query
results."
+ ),
+ )
+ groupby: list[ColumnRef] | None = Field(
+ None,
+ description=(
+ "Columns to group by in aggregate mode (query_mode='aggregate'). "
+ "These become the dimensions for aggregation."
+ ),
+ )
+ metrics: list[ColumnRef] | None = Field(
+ None,
+ description=(
+ "Metrics to aggregate in aggregate mode. "
+ "Each must have an aggregate function (e.g., SUM, COUNT)."
+ ),
+ )
+ filters: list[FilterConfig] | None = Field(None, description="Filters to
apply")
+ row_limit: int = Field(
+ 1000,
+ description="Maximum number of rows",
+ ge=1,
+ le=50000,
+ )
+ order_desc: bool = Field(True, description="Sort in descending order")
+ style_template: str | None = Field(
+ None,
+ description="Optional CSS styles to apply to the rendered template",
+ max_length=10000,
+ )
+
+ @model_validator(mode="after")
+ def validate_query_fields(self) -> "HandlebarsChartConfig":
+ """Validate that the right fields are provided for the query mode."""
+ if self.query_mode == "raw" and not self.columns:
+ raise ValueError(
+ "Handlebars chart in 'raw' query mode requires 'columns'
field. "
+ "Specify which columns to include in the query results."
+ )
+ if self.query_mode == "aggregate" and not self.metrics:
+ raise ValueError(
+ "Handlebars chart in 'aggregate' query mode requires 'metrics'
field. "
+ "Specify at least one metric with an aggregate function."
+ )
+ return self
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing Validator Checks</b></div>
<div id="fix">
The validator should check that groupby is only provided in aggregate mode,
and that metrics have aggregate functions set, to prevent invalid
configurations that could lead to runtime errors or unexpected behavior.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
if self.query_mode == "aggregate" and not self.metrics:
raise ValueError(
"Handlebars chart in 'aggregate' query mode requires
'metrics' field. "
"Specify at least one metric with an aggregate function."
)
if self.groupby and self.query_mode != "aggregate":
raise ValueError("groupby can only be used in aggregate mode")
if self.query_mode == "aggregate":
for metric in self.metrics:
if not metric.aggregate:
raise ValueError("All metrics in aggregate mode must
have an aggregate function set")
return self
````
</div>
</details>
</div>
<small><i>Code Review Run #d0cdaa</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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]