Skip to content

Commit 21ae918

Browse files
I3ekasadpandajoeaminghadersohi
authored
fix(mcp): validate chart queries before persistence (#43128)
Co-authored-by: Bexultan Mustafin <bexultan.mustafin@ffins.kz> Co-authored-by: Joe Li <joe@preset.io> Co-authored-by: Amin Ghadersohi <amin.ghadersohi@gmail.com>
1 parent ca94026 commit 21ae918

2 files changed

Lines changed: 86 additions & 67 deletions

File tree

‎superset/mcp_service/chart/tool/generate_chart.py‎

Lines changed: 59 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ async def generate_chart( # noqa: C901
326326

327327
# Persist the chart only when explicitly requested (save_chart=False by default)
328328
if request.save_chart:
329-
await ctx.report_progress(2, 5, "Creating chart in database")
329+
await ctx.report_progress(2, 5, "Validating chart query")
330330
from superset.commands.chart.create import CreateChartCommand
331331

332332
# Find the dataset to get its numeric ID
@@ -414,6 +414,64 @@ async def generate_chart( # noqa: C901
414414
)
415415
await ctx.debug("Chart name: chart_name=%s" % (chart_name,))
416416

417+
# Compile before persisting. A failed query must not leave a broken
418+
# chart row behind and then rely on a later transaction to delete it.
419+
with event_logger.log_context(action="mcp.generate_chart.compile_check"):
420+
compile_result = _compile_chart(form_data, dataset.id)
421+
if not compile_result.success:
422+
logger.warning(
423+
"Compile check failed before chart creation: %s",
424+
compile_result.error,
425+
)
426+
await ctx.warning(
427+
"Chart compile check failed: error=%s" % (compile_result.error,)
428+
)
429+
from superset.mcp_service.common.error_schemas import (
430+
ChartGenerationError,
431+
)
432+
433+
execution_time = int((time.time() - start_time) * 1000)
434+
error = compile_result.error_obj or ChartGenerationError(
435+
error_type="compile_error",
436+
message="Chart query failed to execute. The chart was not saved.",
437+
details=str(compile_result.error) or "",
438+
suggestions=[
439+
"Check that all columns exist in the dataset",
440+
"Verify aggregate functions are compatible with column types",
441+
"Ensure filters reference valid columns",
442+
"Try simplifying the chart configuration",
443+
],
444+
error_code="CHART_COMPILE_FAILED",
445+
)
446+
return GenerateChartResponse.model_validate(
447+
{
448+
"chart": None,
449+
"error": error.model_dump(),
450+
"form_data": (
451+
_sanitize_generate_chart_form_data_for_llm_context(
452+
form_data
453+
)
454+
),
455+
"performance": {
456+
"query_duration_ms": execution_time,
457+
"cache_status": "error",
458+
"optimization_suggestions": [],
459+
},
460+
"warnings": (
461+
sanitization_warnings
462+
+ runtime_warnings
463+
+ response_warnings
464+
+ compile_result.warnings
465+
),
466+
"success": False,
467+
"schema_version": "2.0",
468+
"api_version": "v1",
469+
}
470+
)
471+
response_warnings.extend(compile_result.warnings)
472+
473+
await ctx.report_progress(3, 5, "Creating chart in database")
474+
417475
try:
418476
with event_logger.log_context(action="mcp.generate_chart.db_write"):
419477
command = CreateChartCommand(
@@ -489,66 +547,6 @@ async def generate_chart( # noqa: C901
489547
# Add any validation warnings (e.g., virtual dataset warnings)
490548
response_warnings.extend(dataset_check.warnings)
491549

492-
# Compile check: execute the chart query to catch runtime errors
493-
await ctx.report_progress(3, 5, "Running compile check (test query)")
494-
with event_logger.log_context(
495-
action="mcp.generate_chart.compile_check"
496-
):
497-
compile_result = _compile_chart(form_data, dataset.id)
498-
if not compile_result.success:
499-
# Query failed — delete the broken chart and return an error
500-
logger.warning(
501-
"Compile check failed for chart %s: %s",
502-
chart_id,
503-
compile_result.error,
504-
)
505-
await ctx.warning(
506-
"Chart compile check failed: error=%s" % (compile_result.error,)
507-
)
508-
from superset.daos.chart import ChartDAO
509-
510-
ChartDAO.delete([chart])
511-
from superset.mcp_service.common.error_schemas import (
512-
ChartGenerationError,
513-
)
514-
515-
execution_time = int((time.time() - start_time) * 1000)
516-
error = compile_result.error_obj or ChartGenerationError(
517-
error_type="compile_error",
518-
message=(
519-
"Chart query failed to execute. The chart was not saved."
520-
),
521-
details=str(compile_result.error) or "",
522-
suggestions=[
523-
"Check that all columns exist in the dataset",
524-
"Verify aggregate functions are compatible "
525-
"with column types",
526-
"Ensure filters reference valid columns",
527-
"Try simplifying the chart configuration",
528-
],
529-
error_code="CHART_COMPILE_FAILED",
530-
)
531-
return GenerateChartResponse.model_validate(
532-
{
533-
"chart": None,
534-
"error": error.model_dump(),
535-
"form_data": (
536-
_sanitize_generate_chart_form_data_for_llm_context(
537-
form_data
538-
)
539-
),
540-
"performance": {
541-
"query_duration_ms": execution_time,
542-
"cache_status": "error",
543-
"optimization_suggestions": [],
544-
},
545-
"success": False,
546-
"schema_version": "2.0",
547-
"api_version": "v1",
548-
}
549-
)
550-
response_warnings.extend(compile_result.warnings)
551-
552550
except CommandException as e:
553551
logger.error("Chart creation failed: %s", e)
554552
await ctx.error("Chart creation failed: error=%s" % (str(e),))

‎tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,8 @@ def __getattr__(self, name: str) -> Any:
475475

476476
async def _generate_saved_chart(
477477
refetch: Any,
478-
) -> tuple[Any, _DetachableSlice]:
478+
compile_result: CompileResult | None = None,
479+
) -> tuple[Any, _DetachableSlice, Mock]:
479480
"""Run generate_chart(save_chart=True) with a chart that detaches on commit.
480481
481482
``refetch`` is used as the ``ChartDAO.find_by_id`` behaviour of the
@@ -503,6 +504,7 @@ async def _generate_saved_chart(
503504
# The instance is detached right after the commit, before any of the reads
504505
# that build the response.
505506
session.refresh.side_effect = lambda _chart: chart.detach()
507+
create_command = Mock(return_value=Mock(run=Mock(return_value=chart)))
506508

507509
with (
508510
patch(
@@ -524,12 +526,12 @@ async def _generate_saved_chart(
524526
patch("superset.mcp_service.auth.has_dataset_access", return_value=True),
525527
patch(
526528
"superset.commands.chart.create.CreateChartCommand",
527-
return_value=Mock(run=Mock(return_value=chart)),
529+
create_command,
528530
),
529531
patch("superset.db.session", session),
530532
patch(
531533
"superset.mcp_service.chart.tool.generate_chart._compile_chart",
532-
return_value=CompileResult(success=True, warnings=[]),
534+
return_value=compile_result or CompileResult(success=True, warnings=[]),
533535
),
534536
patch("superset.daos.chart.ChartDAO", Mock(find_by_id=refetch)),
535537
patch(
@@ -543,7 +545,7 @@ async def _generate_saved_chart(
543545
):
544546
result = await generate_chart(request, ctx=ctx)
545547

546-
return result, chart
548+
return result, chart, create_command
547549

548550

549551
class TestGenerateChartDetachedInstance:
@@ -560,7 +562,7 @@ async def test_detached_chart_is_reported_as_created(self) -> None:
560562
"""A detached instance no longer turns a committed chart into an error."""
561563
refetched = _make_mock_chart()
562564

563-
result, chart = await _generate_saved_chart(
565+
result, chart, _create_command = await _generate_saved_chart(
564566
refetch=Mock(return_value=refetched)
565567
)
566568

@@ -575,7 +577,7 @@ async def test_detached_chart_is_reported_as_created(self) -> None:
575577
@pytest.mark.asyncio
576578
async def test_detached_chart_falls_back_to_captured_scalars(self) -> None:
577579
"""The minimal fallback response never reads the detached instance."""
578-
result, chart = await _generate_saved_chart(
580+
result, chart, _create_command = await _generate_saved_chart(
579581
refetch=Mock(side_effect=SQLAlchemyError("session is gone"))
580582
)
581583

@@ -587,6 +589,25 @@ async def test_detached_chart_falls_back_to_captured_scalars(self) -> None:
587589
assert result.chart.slice_name == "Concurrent chart"
588590
assert result.chart.viz_type == "table"
589591

592+
@pytest.mark.asyncio
593+
async def test_compile_failure_does_not_create_a_chart(self) -> None:
594+
result, chart, create_command = await _generate_saved_chart(
595+
refetch=Mock(),
596+
compile_result=CompileResult(
597+
success=False,
598+
error="column category must appear in GROUP BY",
599+
error_code="CHART_COMPILE_FAILED",
600+
tier="compile",
601+
warnings=["Database returned partial metadata"],
602+
),
603+
)
604+
605+
assert result.success is False
606+
assert result.chart is None
607+
assert result.warnings == ["Database returned partial metadata"]
608+
assert chart._detached is False
609+
create_command.assert_not_called()
610+
590611

591612
class TestChartSerializationEagerLoading:
592613
"""Tests for eager loading fix in generate_chart serialization path."""

0 commit comments

Comments
 (0)