You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gluten.apache.org by ch...@apache.org on 2026/04/21 01:59:43 UTC

(gluten) branch feature/ansi-baseline-workflow updated (94904ab5d9 -> 34738660eb)

This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a change to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git


    from 94904ab5d9 [GLUTEN-10134][VL] Restructure report: JSON-only overview, XML failed suite summary
     add 7c47594690 [GLUTEN-10134][VL] Remove verbose detail tables, filter to spark41 only
     add 566b383507 [GLUTEN-10134][VL] Show failed test names for XML suites with <=3 failures
     add 56818e365e [GLUTEN-10134][VL] Remove Expression Offload Matrix from full report
     add fd97d63003 [GLUTEN-10134][VL] Add Spark 4.1 to report title
     add 940497d192 [GLUTEN-10134][VL] AI analysis: show key findings only, use <br/> in XML suite table
     new c98b7018cb [GLUTEN-10134][VL] Per-Suite Summary: use 4-label columns with Passed+Offload ratio
     new 3fde6ba469 Fix classify_test: use last record's offload status for failed tests
     new ee624d466f Restructure report: record-level stats, cleaner headings, simplified labels
     new 8dfa2c0096 Simplify analyze-ansi.py: English prompt, remove dead code, add AI disclaimer
     new 84febca805 Restore analyze-ansi-results.py (deleted by mistake)
     new 2c62c21a81 Fix analyze-only: increase run search window from 15 to 50
     new 34738660eb Cleanup: remove dead analyze-ansi-results.py, drop --mode from workflow

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .github/scripts/analyze-ansi-results.py  | 722 -------------------------------
 .github/scripts/analyze-ansi.py          | 716 ++++++++----------------------
 .github/workflows/velox_backend_ansi.yml |  19 +-
 3 files changed, 201 insertions(+), 1256 deletions(-)
 delete mode 100644 .github/scripts/analyze-ansi-results.py


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org


(gluten) 05/07: Restore analyze-ansi-results.py (deleted by mistake)

Posted by ch...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a commit to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit 84febca805d15d36675fd3091e4f56231dbde84a
Author: Chang chen <ch...@apache.org>
AuthorDate: Tue Apr 21 09:25:17 2026 +0800

    Restore analyze-ansi-results.py (deleted by mistake)
    
    Co-Authored-By: Claude Opus 4 <no...@anthropic.com>
---
 .github/scripts/analyze-ansi-results.py | 722 ++++++++++++++++++++++++++++++++
 1 file changed, 722 insertions(+)

diff --git a/.github/scripts/analyze-ansi-results.py b/.github/scripts/analyze-ansi-results.py
new file mode 100644
index 0000000000..4a17d96121
--- /dev/null
+++ b/.github/scripts/analyze-ansi-results.py
@@ -0,0 +1,722 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Analyze ANSI mode test results from surefire XML and/or test logs.
+
+Supports two input formats:
+  --format xml  : Parse surefire XML reports (CI artifacts)
+  --format log  : Parse test log files (local verify-ansi-expressions.sh output)
+
+Both formats are merged when available: XML provides authoritative pass/fail/skip,
+logs provide expression-level offload/fallback data from EXPRESSION_OFFLOAD_SUMMARY blocks.
+
+Three-color classification:
+  🟢 Passed + Offload  — test passes natively in Velox ANSI mode
+  🟡 Failed + Offload  — test runs in Velox but fails (needs ANSI fix)
+  🔴 Passed + Fallback — test passes but fell back to Spark (Velox can't handle it)
+
+Options:
+  --ai           Call GitHub Models API for analysis
+  --pr-comment   Post report as PR comment
+  --report-dir   Directory containing surefire XML reports (default: ./test-reports/)
+  --log-dir      Directory containing test log files
+  --log          Single log file to parse
+
+Environment variables:
+  GH_TOKEN       — GitHub token for PR comments and GitHub Models API
+  AI_MODEL       — Model name for GitHub Models API (default: gpt-4o)
+  PR_NUMBER      — PR number to comment on
+  TRIGGERED_BY   — GitHub user who triggered the analysis
+  RUN_ID         — GitHub Actions run ID
+"""
+import argparse
+import glob
+import json
+import os
+import re
+import subprocess
+import sys
+import xml.etree.ElementTree as ET
+from collections import defaultdict, OrderedDict
+from pathlib import Path
+
+AI_ENDPOINT = "https://models.inference.ai.azure.com/chat/completions"
+ANSI_RE = re.compile(r'\x1b\[[0-9;]*m')
+
+# Log parsing patterns (from analyze-ansi-test-log.py)
+SUITE_RE = re.compile(r'^(Gluten\w+Suite):$')
+OFFLOAD_RE = re.compile(r"^'(.+)' offload to gluten$")
+FALLBACK_RE = re.compile(r"^'(.+)' NOT use gluten$")
+PASSED_RE = re.compile(r'^- (.+?)(?:\s+\(\d+.*\))?$')
+FAILED_RE = re.compile(r'^- (.+?) \*\*\* FAILED \*\*\*(?:\s+\(\d+.*\))?$')
+IGNORED_RE = re.compile(r'^- (.+?) !!! IGNORED !!!$')
+VALIDATION_FAILED_RE = re.compile(r'Validation failed')
+GLUTEN_CHECK_RE = re.compile(r'glutenCheck(?:Expression|ExceptionInExpression)')
+
+NO_EXCEPTION_RE = re.compile(
+    r'Expected exception .+ to be thrown, but no exception was thrown')
+MSG_MISMATCH_RE = re.compile(
+    r"Expected error message containing '(.+?)' but got '(.+?)'")
+WRONG_EXCEPTION_RE = re.compile(
+    r'Expected (\S+) but got (\S+):')
+
+# EXPRESSION_OFFLOAD_SUMMARY markers
+OFFLOAD_SUMMARY_BEGIN = 'EXPRESSION_OFFLOAD_SUMMARY_BEGIN'
+OFFLOAD_SUMMARY_END = 'EXPRESSION_OFFLOAD_SUMMARY_END'
+
+
+# ---------------------------------------------------------------------------
+# Surefire XML parsing
+# ---------------------------------------------------------------------------
+
+def parse_surefire_reports(base_dir):
+    """Parse all surefire XML reports and return structured test results."""
+    results = []
+    xml_files = glob.glob(f"{base_dir}/**/TEST-*.xml", recursive=True)
+    if not xml_files:
+        return results
+
+    for xml_path in xml_files:
+        try:
+            tree = ET.parse(xml_path)
+        except ET.ParseError:
+            continue
+        suite = tree.getroot()
+        suite_name = suite.get("name", Path(xml_path).stem)
+        job_name = _infer_job_name(xml_path)
+
+        for tc in suite.findall("testcase"):
+            test_name = tc.get("name", "unknown")
+            classname = tc.get("classname", suite_name)
+            time_s = float(tc.get("time", "0"))
+
+            failure = tc.find("failure")
+            error = tc.find("error")
+            skipped = tc.find("skipped")
+
+            if skipped is not None:
+                status = "SKIPPED"
+                message = skipped.get("message", "")
+            elif failure is not None:
+                status = "FAILED"
+                message = (failure.get("message") or failure.text or "")[:500]
+            elif error is not None:
+                status = "ERROR"
+                message = (error.get("message") or error.text or "")[:500]
+            else:
+                status = "PASSED"
+                message = ""
+
+            results.append({
+                "suite": classname,
+                "test": test_name,
+                "status": status,
+                "message": message,
+                "time": time_s,
+                "job": job_name,
+            })
+    return results
+
+
+def _infer_job_name(xml_path):
+    parts = Path(xml_path).parts
+    for p in parts:
+        if "spark-test-" in p:
+            return p
+    return "unknown"
+
+
+def _short_job_name(job):
+    """Shorten job name for table display."""
+    job = job.replace("spark-test-", "").replace("-report", "")
+    return job or "unknown"
+
+
+# ---------------------------------------------------------------------------
+# Log file parsing
+# ---------------------------------------------------------------------------
+
+def parse_log(path):
+    """Parse test log and return list of test-level results."""
+    lines = []
+    with open(path, 'r', errors='replace') as f:
+        for raw_line in f:
+            lines.append(ANSI_RE.sub('', raw_line).strip())
+
+    tests = []
+    current_suite = None
+    test_entries = []
+
+    for i, line in enumerate(lines):
+        if not line:
+            continue
+        m = SUITE_RE.match(line)
+        if m:
+            current_suite = m.group(1)
+            continue
+        m = OFFLOAD_RE.match(line)
+        if m:
+            test_entries.append((i, current_suite, m.group(1), None))
+            continue
+        m = FALLBACK_RE.match(line)
+        if m:
+            test_entries.append((i, current_suite, m.group(1), None))
+            continue
+        m = FAILED_RE.match(line)
+        if m:
+            test_entries.append((i, current_suite, m.group(1), 'FAILED'))
+            continue
+        m = IGNORED_RE.match(line)
+        if m:
+            test_entries.append((i, current_suite, m.group(1), 'IGNORED'))
+            continue
+        m = PASSED_RE.match(line)
+        if m and not VALIDATION_FAILED_RE.search(line):
+            test_entries.append((i, current_suite, m.group(1), 'PASSED'))
+            continue
+
+    test_map = OrderedDict()
+    for line_idx, suite, name, result in test_entries:
+        key = (suite, name)
+        if key not in test_map:
+            test_map[key] = {
+                'suite': suite or '(unknown)',
+                'test': name,
+                'result': result,
+                'start_line': line_idx,
+            }
+        else:
+            entry = test_map[key]
+            if result is not None:
+                entry['result'] = result
+            entry['start_line'] = min(entry['start_line'], line_idx)
+
+    test_list = list(test_map.values())
+    for i, t in enumerate(test_list):
+        if i + 1 < len(test_list):
+            t['end_line'] = test_list[i + 1]['start_line']
+        else:
+            t['end_line'] = len(lines)
+
+    results = []
+    for t in test_list:
+        if t['result'] == 'IGNORED':
+            has_fallback = False
+            has_velox = False
+            fail_cause = None
+        else:
+            has_fallback = False
+            has_velox = False
+            fail_cause = None
+            for j in range(t['start_line'], t['end_line']):
+                if VALIDATION_FAILED_RE.search(lines[j]):
+                    has_fallback = True
+                if GLUTEN_CHECK_RE.search(lines[j]):
+                    has_velox = True
+                if t['result'] == 'FAILED' and fail_cause is None:
+                    if NO_EXCEPTION_RE.search(lines[j]):
+                        fail_cause = 'NO_EXCEPTION'
+                    elif MSG_MISMATCH_RE.search(lines[j]):
+                        fail_cause = 'MSG_MISMATCH'
+                    elif WRONG_EXCEPTION_RE.search(lines[j]):
+                        fail_cause = 'WRONG_EXCEPTION'
+            if t['result'] == 'FAILED' and fail_cause is None:
+                fail_cause = 'OTHER'
+
+        results.append({
+            'suite': t['suite'],
+            'test': t['test'],
+            'fallback': has_fallback,
+            'velox': has_velox,
+            'result': t['result'] or 'PASSED',
+            'fail_cause': fail_cause,
+        })
+
+    return results
+
+
+# ---------------------------------------------------------------------------
+# EXPRESSION_OFFLOAD_SUMMARY block parsing
+# ---------------------------------------------------------------------------
+
+def parse_offload_summary_from_logs(log_paths):
+    """Parse EXPRESSION_OFFLOAD_SUMMARY blocks from log files.
+
+    Returns dict: {(suite, test_name): [OffloadRecord...]}
+    where each record is {method, expression, meta, offload, status}.
+    """
+    all_records = {}
+
+    for path in log_paths:
+        in_block = False
+        current_suite = None
+        current_test = None
+
+        with open(path, 'r', errors='replace') as f:
+            for raw_line in f:
+                line = ANSI_RE.sub('', raw_line).strip()
+                # Strip log4j prefix if present
+                if '] ' in line:
+                    line = line[line.rindex('] ') + 2:]
+                # Strip SLF4J/logback prefix: "HH:MM:SS.mmm WARN classname: content"
+                m = re.match(
+                    r'\d{2}:\d{2}:\d{2}\.\d+ \w+ [\w.$]+:\s*(.*)', line)
+                if m:
+                    line = m.group(1)
+
+                if OFFLOAD_SUMMARY_BEGIN in line:
+                    in_block = True
+                    continue
+                if OFFLOAD_SUMMARY_END in line:
+                    in_block = False
+                    current_suite = None
+                    current_test = None
+                    continue
+                if not in_block:
+                    continue
+
+                stripped = line.strip()
+                if stripped.endswith(':') and not stripped.startswith(('N|', 'E|')):
+                    if '|' not in stripped:
+                        name = stripped[:-1].strip()
+                        if current_suite is None:
+                            current_suite = name
+                        else:
+                            current_test = name
+                    continue
+
+                if '|' in stripped and stripped[0] in ('N', 'E'):
+                    parts = stripped.split('|')
+                    if len(parts) >= 5:
+                        record = {
+                            'method': 'checkException' if parts[0] == 'E' else 'checkExpression',
+                            'expression': parts[1],
+                            'meta': parts[2],
+                            'offload': parts[3],
+                            'status': parts[4],
+                        }
+                        key = (current_suite, current_test)
+                        all_records.setdefault(key, []).append(record)
+
+    return all_records
+
+
+# ---------------------------------------------------------------------------
+# Classification
+# ---------------------------------------------------------------------------
+
+def classify_test(status, has_fallback, has_offload_data):
+    """Assign three-color classification."""
+    if status == "SKIPPED":
+        return "⚪", "Skipped"
+    if has_fallback:
+        if status == "PASSED":
+            return "🔴", "Passed+Fallback"
+        return "🔴", "Failed+Fallback"
+    if not has_offload_data:
+        if status == "PASSED":
+            return "⚪", "Passed (no data)"
+        return "🟡", "Failed (no data)"
+    if status == "PASSED":
+        return "🟢", "Passed+Offload"
+    if status in ("FAILED", "ERROR"):
+        return "🟡", "Failed+Offload"
+    return "🟡", "Failed"
+
+
+def determine_fallback(test_key, offload_records):
+    """Determine fallback status and whether offload data exists."""
+    records = offload_records.get(test_key, [])
+    if not records:
+        return False, False
+    return any(r['offload'] == 'FALLBACK' for r in records), True
+
+
+def build_summary(results, offload_records=None):
+    """Build summary with three-color classification."""
+    offload_records = offload_records or {}
+    summary = {
+        "total": len(results),
+        "by_color": defaultdict(int),
+        "by_job": defaultdict(lambda: defaultdict(int)),
+        "failures": [],
+    }
+    for t in results:
+        suite = t.get("suite", "")
+        test = t.get("test", "")
+        status = t.get("status", "PASSED")
+
+        has_fallback = t.get("fallback", False)
+        has_offload_data = False
+        if offload_records:
+            test_key = (suite.split('.')[-1], test)
+            fb, has_data = determine_fallback(test_key, offload_records)
+            has_fallback = has_fallback or fb
+            has_offload_data = has_data
+
+        color, label = classify_test(status, has_fallback, has_offload_data)
+        t["color"] = color
+        t["label"] = label
+        t["fallback"] = has_fallback
+        summary["by_color"][label] += 1
+        job = t.get("job", "unknown")
+        summary["by_job"][job][label] += 1
+        if status in ("FAILED", "ERROR"):
+            summary["failures"].append(t)
+    return summary
+
+
+# ---------------------------------------------------------------------------
+# Report generation
+# ---------------------------------------------------------------------------
+
+def format_markdown_report(summary, results, ai_analysis=None):
+    """Generate markdown report."""
+    lines = ["## ANSI Mode Test Analysis Report\n"]
+
+    lines.append("### Overview\n")
+    lines.append(f"Total tests: **{summary['total']}**\n")
+    lines.append("| Classification | Count |")
+    lines.append("|---|---|")
+    for label in ["Passed+Offload", "Failed+Offload", "Passed+Fallback",
+                  "Failed+Fallback", "Failed", "Passed (no data)",
+                  "Failed (no data)", "Skipped"]:
+        count = summary["by_color"].get(label, 0)
+        if count > 0:
+            color = {"Passed+Offload": "🟢", "Failed+Offload": "🟡",
+                     "Passed+Fallback": "🔴", "Failed+Fallback": "🔴",
+                     "Failed": "🟡", "Passed (no data)": "⚪",
+                     "Failed (no data)": "🟡", "Skipped": "⚪"}.get(label, "")
+            lines.append(f"| {color} {label} | {count} |")
+    lines.append("")
+
+    lines.append("### Per-Job Breakdown\n")
+    for job, counts in sorted(summary["by_job"].items()):
+        lines.append(f"**{job}**")
+        for label, count in sorted(counts.items()):
+            lines.append(f"- {label}: {count}")
+        lines.append("")
+
+    if summary["failures"]:
+        lines.append("### Failed Tests (sample, max 50)\n")
+        lines.append("| Suite | Test | Job | Color | Message |")
+        lines.append("|---|---|---|---|---|")
+        for t in summary["failures"][:50]:
+            msg = t.get("message", "")[:200].replace("|", "\\|").replace("\n", " ")
+            job = _short_job_name(t.get("job", ""))
+            lines.append(
+                f"| {t['suite'].split('.')[-1]} | {t['test']} "
+                f"| {job} | {t['color']} {t['label']} | {msg} |")
+        if len(summary["failures"]) > 50:
+            lines.append(f"\n*...and {len(summary['failures']) - 50} more failures*\n")
+        lines.append("")
+
+    if ai_analysis:
+        lines.append("### AI Analysis\n")
+        lines.append(ai_analysis)
+        lines.append("")
+
+    triggered_by = os.environ.get("TRIGGERED_BY", "unknown")
+    run_id = os.environ.get("RUN_ID", "")
+    lines.append(f"\n---\n*Triggered by @{triggered_by} | "
+                 f"[Workflow run](../actions/runs/{run_id})*")
+    return "\n".join(lines)
+
+
+def format_log_table(tests, fallback_only=False, failed_only=False, suite_filter=None):
+    """Print table for log-based analysis (local usage)."""
+    filtered = tests
+    if suite_filter:
+        filtered = [t for t in filtered if suite_filter in t['suite']]
+    if fallback_only:
+        filtered = [t for t in filtered if t['fallback']]
+    if failed_only:
+        filtered = [t for t in filtered if t['result'] == 'FAILED']
+
+    if not filtered:
+        print("No matching tests found.")
+        return
+
+    sw = max(max(len(t['suite']) for t in filtered), len('Suite'))
+    tw = max(max(len(t['test']) for t in filtered), len('Test'))
+
+    def velox_str(t):
+        if t['result'] == 'IGNORED':
+            return 'N/A'
+        return 'yes' if t['velox'] else 'no'
+
+    def fallback_str(t):
+        if t['result'] == 'IGNORED':
+            return 'N/A'
+        return 'found' if t['fallback'] else 'not found'
+
+    def cause_str(t):
+        return t.get('fail_cause') or ''
+
+    has_failures = any(t['result'] == 'FAILED' for t in filtered)
+    if has_failures:
+        cw = max(max((len(cause_str(t)) for t in filtered), default=5), len('Cause'))
+        header = (f"| {'Suite':<{sw}} | {'Test':<{tw}} | Velox | Fallback  "
+                  f"| Result  | {'Cause':<{cw}} |")
+        sep = (f"|{'-' * (sw + 2)}|{'-' * (tw + 2)}|-------|--------"
+               f"---|---------|{'-' * (cw + 2)}|")
+    else:
+        header = f"| {'Suite':<{sw}} | {'Test':<{tw}} | Velox | Fallback  | Result  |"
+        sep = f"|{'-' * (sw + 2)}|{'-' * (tw + 2)}|-------|-----------|---------|"
+    print(header)
+    print(sep)
+    for t in filtered:
+        v = velox_str(t)
+        fb = fallback_str(t)
+        if has_failures:
+            c = cause_str(t)
+            print(f"| {t['suite']:<{sw}} | {t['test']:<{tw}} | {v:<5} | {fb:<9} "
+                  f"| {t['result']:<7} | {c:<{cw}} |")
+        else:
+            print(f"| {t['suite']:<{sw}} | {t['test']:<{tw}} | {v:<5} | {fb:<9} "
+                  f"| {t['result']:<7} |")
+
+    print()
+    total = len(filtered)
+    passed = sum(1 for t in filtered if t['result'] == 'PASSED')
+    failed = sum(1 for t in filtered if t['result'] == 'FAILED')
+    ignored = sum(1 for t in filtered if t['result'] == 'IGNORED')
+    velox_yes = sum(1 for t in filtered if t.get('velox'))
+    velox_no = sum(1 for t in filtered if not t.get('velox') and t['result'] != 'IGNORED')
+    fb_found = sum(1 for t in filtered if t['fallback'])
+    print(f"Total: {total} | Velox: {velox_yes} | No Velox: {velox_no} | "
+          f"Fallback: {fb_found}")
+    print(f"Passed: {passed} | Failed: {failed} | Ignored: {ignored}")
+
+    if failed > 0:
+        causes = {}
+        for t in filtered:
+            c = t.get('fail_cause')
+            if c:
+                causes[c] = causes.get(c, 0) + 1
+        cause_parts = [f"{c}: {n}" for c, n in sorted(causes.items())]
+        print(f"Failure causes: {' | '.join(cause_parts)}")
+
+    print()
+    print("Per-suite summary:")
+    suites = OrderedDict()
+    for t in filtered:
+        s = t['suite']
+        if s not in suites:
+            suites[s] = {'total': 0, 'velox': 0, 'no_velox': 0, 'fb_found': 0,
+                         'passed': 0, 'failed': 0, 'ignored': 0}
+        suites[s]['total'] += 1
+        if t.get('velox'):
+            suites[s]['velox'] += 1
+        elif t['result'] != 'IGNORED':
+            suites[s]['no_velox'] += 1
+        if t['fallback']:
+            suites[s]['fb_found'] += 1
+        suites[s][t['result'].lower()] += 1
+
+    sn_w = max(len(s) for s in suites)
+    print(f"| {'Suite':<{sn_w}} | Total | Velox | No Velox | Fallback "
+          f"| Passed | Failed | Ignored |")
+    print(f"|{'-' * (sn_w + 2)}|-------|-------|----------|----------|"
+          f"--------|--------|---------|")
+    for s, c in suites.items():
+        print(f"| {s:<{sn_w}} | {c['total']:>5} | {c['velox']:>5} | "
+              f"{c['no_velox']:>8} | {c['fb_found']:>8} | {c['passed']:>6} | "
+              f"{c['failed']:>6} | {c['ignored']:>7} |")
+
+
+# ---------------------------------------------------------------------------
+# AI analysis
+# ---------------------------------------------------------------------------
+
+def call_github_models_api(summary, failures_sample):
+    """Call GitHub Models API for AI analysis."""
+    token = os.environ.get("GH_TOKEN")
+    model = os.environ.get("AI_MODEL", "gpt-4o")
+    if not token:
+        return None
+
+    failure_text = "\n".join(
+        f"- {t['suite'].split('.')[-1]}.{t['test']}: {t['color']} {t['label']} — "
+        f"{t.get('message', '')[:200]}"
+        for t in failures_sample[:30]
+    )
+
+    prompt = f"""Analyze these ANSI SQL mode test results from Apache Gluten (Velox backend).
+
+Summary:
+- Total tests: {summary['total']}
+- 🟢 Passed+Offload (native Velox ANSI): {summary['by_color'].get('Passed+Offload', 0)}
+- 🟡 Failed+Offload (Velox ran but failed): {summary['by_color'].get('Failed+Offload', 0)}
+- 🔴 Passed+Fallback (fell back to Spark): {summary['by_color'].get('Passed+Fallback', 0)}
+
+Sample failures:
+{failure_text}
+
+Provide a brief analysis (under 500 words):
+1. Key failure patterns and root causes
+2. Which expression types need ANSI implementation work
+3. Priority recommendations for fixing"""
+
+    try:
+        import requests
+        resp = requests.post(
+            AI_ENDPOINT,
+            headers={
+                "Authorization": f"Bearer {token}",
+                "Content-Type": "application/json",
+            },
+            json={
+                "model": model,
+                "messages": [{"role": "user", "content": prompt}],
+                "max_tokens": 1000,
+            },
+            timeout=60,
+        )
+        if resp.status_code == 200:
+            return resp.json()["choices"][0]["message"]["content"]
+        else:
+            return (f"*AI analysis unavailable (HTTP {resp.status_code}). "
+                    f"The commenter may not have GitHub Models API access.*")
+    except Exception as e:
+        return f"*AI analysis unavailable: {e}*"
+
+
+# ---------------------------------------------------------------------------
+# Output helpers
+# ---------------------------------------------------------------------------
+
+def post_pr_comment(markdown):
+    pr_number = os.environ.get("PR_NUMBER")
+    if not pr_number:
+        print("PR_NUMBER not set, skipping PR comment")
+        return
+    try:
+        subprocess.run(
+            ["gh", "pr", "comment", pr_number, "--body", markdown],
+            check=True, timeout=30,
+        )
+        print(f"Posted comment to PR #{pr_number}")
+    except (subprocess.CalledProcessError, subprocess.TimeoutExpired,
+            FileNotFoundError) as e:
+        print(f"Failed to post PR comment: {e}")
+
+
+def write_job_summary(markdown):
+    summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
+    if summary_path:
+        with open(summary_path, "a") as f:
+            f.write(markdown)
+        print("Wrote Job Summary")
+
+
+# ---------------------------------------------------------------------------
+# Main
+# ---------------------------------------------------------------------------
+
+def main():
+    parser = argparse.ArgumentParser(
+        description='Analyze Gluten ANSI mode test results')
+    parser.add_argument('--format', choices=['xml', 'log'], default='xml',
+                        help='Input format: xml (surefire reports) or log (test logs)')
+    parser.add_argument('--report-dir', default='./test-reports/',
+                        help='Directory with surefire XML reports')
+    parser.add_argument('--log-dir', default=None,
+                        help='Directory with test log files')
+    parser.add_argument('--log', default=None,
+                        help='Single log file to parse')
+    parser.add_argument('--ai', action='store_true',
+                        help='Call GitHub Models API for analysis')
+    parser.add_argument('--pr-comment', action='store_true',
+                        help='Post report as PR comment')
+    parser.add_argument('--fallback-only', action='store_true',
+                        help='Show only tests that fell back to Spark (log mode)')
+    parser.add_argument('--failed-only', action='store_true',
+                        help='Show only failed tests (log mode)')
+    parser.add_argument('--suite', type=str, default=None,
+                        help='Filter by suite name (log mode)')
+    args = parser.parse_args()
+
+    offload_records = {}
+
+    if args.format == 'log':
+        # Log-based analysis (local mode)
+        log_path = args.log
+        if not log_path:
+            print("--log is required for --format log")
+            sys.exit(1)
+        tests = parse_log(log_path)
+        if not tests:
+            print(f"No tests found in {log_path}")
+            sys.exit(1)
+
+        offload_records = parse_offload_summary_from_logs([log_path])
+
+        for t in tests:
+            key = (t['suite'], t['test'])
+            records = offload_records.get(key, [])
+            if records:
+                t['fallback'] = any(r['offload'] == 'FALLBACK' for r in records)
+                t['velox'] = any(r['offload'] == 'OFFLOAD' for r in records)
+
+        format_log_table(tests, fallback_only=args.fallback_only,
+                         failed_only=args.failed_only, suite_filter=args.suite)
+        return
+
+    # XML-based analysis (CI mode)
+    results = parse_surefire_reports(args.report_dir)
+
+    # Parse offload summary from log files if available
+    log_paths = []
+    if args.log_dir:
+        log_paths = glob.glob(f"{args.log_dir}/**/*.log", recursive=True)
+        log_paths += glob.glob(f"{args.log_dir}/**/*.txt", recursive=True)
+    if args.log:
+        log_paths.append(args.log)
+    if log_paths:
+        offload_records = parse_offload_summary_from_logs(log_paths)
+
+    if not results:
+        msg = ("## ANSI Mode Test Analysis\n\nNo test reports found. "
+               "Build may have failed — check individual job logs.")
+        if args.pr_comment:
+            post_pr_comment(msg)
+        write_job_summary(msg)
+        print("No surefire reports found")
+        sys.exit(0)
+
+    summary = build_summary(results, offload_records)
+
+    ai_analysis = None
+    if args.ai:
+        ai_analysis = call_github_models_api(summary, summary["failures"])
+
+    report = format_markdown_report(summary, results, ai_analysis)
+
+    if args.pr_comment:
+        post_pr_comment(report)
+    else:
+        print(report)
+    write_job_summary(report)
+
+    print(f"Analysis complete: {summary['total']} tests, "
+          f"{len(summary['failures'])} failures")
+    if offload_records:
+        print(f"Offload records parsed from {len(log_paths)} log file(s), "
+              f"{len(offload_records)} test entries")
+
+
+if __name__ == "__main__":
+    main()


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org


(gluten) 03/07: Restructure report: record-level stats, cleaner headings, simplified labels

Posted by ch...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a commit to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit ee624d466f5b5c39a08c978b7b65ea7c6286733c
Author: Chang chen <ch...@apache.org>
AuthorDate: Tue Apr 21 09:05:45 2026 +0800

    Restructure report: record-level stats, cleaner headings, simplified labels
    
    - Switch stats unit from test to record (expression) level
    - Rename labels: Passed+Offload→Passed, Passed+Fallback→Fallback, Failed+Offload→Failed
    - Restructure headings: # title, > [!NOTE] callout, ## ANSI Offload, ## Other
    - Remove Failed+Fallback category
    - Rename JSON/XML terminology to ANSI Offload/Other suites
    
    Co-Authored-By: Claude Opus 4 <no...@anthropic.com>
---
 .github/scripts/analyze-ansi.py | 201 +++++++++++++++++++++-------------------
 1 file changed, 106 insertions(+), 95 deletions(-)

diff --git a/.github/scripts/analyze-ansi.py b/.github/scripts/analyze-ansi.py
index 26f4200e2d..649a734f0a 100644
--- a/.github/scripts/analyze-ansi.py
+++ b/.github/scripts/analyze-ansi.py
@@ -205,64 +205,67 @@ def _infer_job_name(xml_path):
 # ANALYSIS LAYER
 # ===========================================================================
 
-def classify_test(status, has_fallback, has_offload_data, last_record_fallback=None):
-    """Unified three-color classification.
+def classify_record(offload_status, record_status):
+    """Classify a single record (expression-level).
 
-    For failed tests, last_record_fallback (bool) determines Offload vs Fallback
-    because failure always occurs at the last record.
+    offload_status: "OFFLOAD" or "FALLBACK"
+    record_status: "PASS" or "FAIL"
     """
+    is_pass = record_status in ("PASSED", "PASS")
+    is_fallback = offload_status == "FALLBACK"
+    if is_fallback:
+        if is_pass:
+            return "🔴", "Fallback"
+        return "🔴", "Failed+Fallback"
+    if is_pass:
+        return "🟢", "Passed"
+    return "🟡", "Failed"
+
+
+def classify_test_for_xml(status):
+    """Classify XML tests (no offload data)."""
     is_pass = status in ("PASSED", "PASS")
     is_skip = status in ("SKIPPED", "SKIP")
-    is_fail = status in ("FAILED", "ERROR", "FAIL")
     if is_skip:
         return "⚪", "Skipped"
-    if not has_offload_data:
-        if is_pass:
-            return "⚪", "Passed (no data)"
-        return "🟡", "Failed (no data)"
-    if is_fail:
-        if last_record_fallback:
-            return "🔴", "Failed+Fallback"
-        return "🟡", "Failed+Offload"
-    if has_fallback:
-        return "🔴", "Passed+Fallback"
     if is_pass:
-        return "🟢", "Passed+Offload"
-    return "🟡", "Failed"
+        return "⚪", "Passed (no data)"
+    return "🟡", "Failed (no data)"
 
 
 def analyze_json_tests(suites):
-    """Analyze JSON data at test level. Returns summary dict + flat test list."""
-    tests = []
+    """Analyze JSON data at record (expression) level. Returns flat record list."""
+    records_out = []
     for suite_data in suites:
         suite_name = suite_data.get("suite", "")
         category = suite_data.get("category", "")
         for t in suite_data.get("tests", []):
-            records = t.get("records", [])
-            has_fallback = any(r.get("offload") == "FALLBACK" for r in records)
-            has_offload_data = len(records) > 0
-            last_record_fallback = (records[-1].get("offload") == "FALLBACK") if records else None
-            color, label = classify_test(
-                t.get("status", "PASSED"), has_fallback, has_offload_data,
-                last_record_fallback)
-            tests.append({
-                "suite": suite_name,
-                "test": t["name"],
-                "status": t.get("status", "PASSED"),
-                "color": color,
-                "label": label,
-                "category": category,
-                "has_fallback": has_fallback,
-                "records": records,
-            })
-    return tests
+            test_status = t.get("status", "PASSED")
+            for rec in t.get("records", []):
+                offload = rec.get("offload", "")
+                rec_status = rec.get("status", "PASS")
+                color, label = classify_record(offload, rec_status)
+                records_out.append({
+                    "suite": suite_name,
+                    "test": t["name"],
+                    "test_status": test_status,
+                    "status": rec_status,
+                    "color": color,
+                    "label": label,
+                    "category": category,
+                    "offload": offload,
+                    "expression": rec.get("expression", ""),
+                    "failCause": rec.get("failCause", ""),
+                    "meta": rec.get("meta", {}),
+                })
+    return records_out
 
 
 def analyze_xml_tests(xml_results):
     """Analyze surefire XML at test method level."""
     tests = []
     for t in xml_results:
-        color, label = classify_test(t["status"], False, False)
+        color, label = classify_test_for_xml(t["status"])
         tests.append({
             "suite": t["suite"],
             "test": t["test"],
@@ -276,26 +279,22 @@ def analyze_xml_tests(xml_results):
     return tests
 
 
-def build_summary(json_tests, xml_tests):
-    """Build unified summary from both data sources."""
+def build_summary(json_records, xml_tests):
+    """Build unified summary. json_records are at record (expression) level."""
     by_color = defaultdict(int)
     failures = []
     total = 0
 
-    for t in json_tests:
+    for r in json_records:
         total += 1
-        by_color[t["label"]] += 1
-        if t["status"] in ("FAILED", "ERROR", "FAIL"):
-            fail_cause = ""
-            for r in t.get("records", []):
-                if r.get("failCause"):
-                    fail_cause = r["failCause"]
-                    break
+        by_color[r["label"]] += 1
+        if r["status"] in ("FAILED", "ERROR", "FAIL"):
+            fail_cause = r.get("failCause", "")
             failures.append({
-                "suite": t["suite"],
-                "test": t["test"],
-                "color": t["color"],
-                "label": t["label"],
+                "suite": r["suite"],
+                "test": r["test"],
+                "color": r["color"],
+                "label": r["label"],
                 "message": fail_cause,
                 "source": "json",
             })
@@ -314,11 +313,17 @@ def build_summary(json_tests, xml_tests):
                 "source": "xml",
             })
 
+    # Count unique tests from JSON for the header
+    json_test_names = set()
+    for r in json_records:
+        json_test_names.add((r["suite"], r["test"]))
+
     return {
         "total": total,
         "by_color": dict(by_color),
         "failures": failures,
-        "json_test_count": len(json_tests),
+        "json_record_count": len(json_records),
+        "json_test_count": len(json_test_names),
         "xml_test_count": len(xml_tests),
     }
 
@@ -434,62 +439,68 @@ def _worse(a, b):
 # OUTPUT LAYER
 # ===========================================================================
 
-def format_summary(summary, json_tests, suites=None):
-    """Format test-level summary as markdown."""
-    lines = ["## ANSI Mode Test Analysis Report (Spark 4.1)\n"]
-    json_total = summary["json_test_count"]
+def format_summary(summary, json_records, suites=None):
+    """Format record-level summary as markdown."""
+    lines = ["# ANSI Mode Test Analysis Report (Spark 4.1)\n"]
+    lines.append("> [!NOTE]")
+    lines.append("> Expression-level ANSI mode offload coverage analysis.")
+    lines.append("> Test config: `spark.sql.ansi.enabled=true`,"
+                 " `spark.gluten.sql.ansiFallback.enabled=false`.")
+    lines.append("> - **Passed (🟢)**: Velox correctly handles ANSI semantics")
+    lines.append("> - **Fallback (🔴)**: Expression falls back to Spark execution,"
+                 " needs ANSI support in Velox")
+    lines.append("> - **Failed (🟡)**: Velox executes but ANSI error behavior"
+                 " differs from Spark, needs exception handling fix\n")
+    json_test_count = summary["json_test_count"]
+    json_record_count = summary["json_record_count"]
     xml_total = summary["xml_test_count"]
-    lines.append(f"**JSON tests: {json_total}** | "
-                 f"**XML suites: {xml_total} tests**\n")
+    lines.append(f"**ANSI Offload suites: {json_test_count} tests, "
+                 f"{json_record_count} records** | "
+                 f"**Other suites: {xml_total} tests**\n")
+
+    # --- ANSI Offload section ---
+    lines.append("## ANSI Offload\n")
 
-    # --- Overview: JSON-only three-color stats ---
-    lines.append("### Overview (JSON Expression Tests)\n")
+    # --- Overview: record-level stats ---
+    lines.append("### Overview (ANSI Offload Expression Records)\n")
     lines.append("| Classification | Count | % |")
     lines.append("|---|---|---|")
-    json_labels = ["Passed+Offload", "Failed+Offload", "Passed+Fallback",
-                   "Failed+Fallback", "Failed"]
-    color_map = {"Passed+Offload": "🟢", "Failed+Offload": "🟡",
-                 "Passed+Fallback": "🔴", "Failed+Fallback": "🔴",
-                 "Failed": "🟡"}
+    json_labels = ["Passed", "Failed", "Fallback"]
+    color_map = {"Passed": "🟢", "Failed": "🟡",
+                 "Fallback": "🔴"}
     for label in json_labels:
         count = summary["by_color"].get(label, 0)
         if count > 0:
             color = color_map.get(label, "")
-            pct = count * 100 / json_total if json_total else 0
+            pct = count * 100 / json_record_count if json_record_count else 0
             lines.append(f"| {color} {label} | {count} | {pct:.1f}% |")
     lines.append("")
 
-    # --- Per-Suite Summary (JSON only) ---
+    # --- Per-Suite Summary (record-level) ---
     if suites:
         lines.append("### Per-Suite Summary\n")
-        lines.append("| Suite | 🟢 Passed+Offload | 🟡 Failed+Offload "
-                     "| 🔴 Passed+Fallback | 🔴 Failed+Fallback |")
-        lines.append("|---|---|---|---|---|")
+        lines.append("| Suite | 🟢 Passed | 🟡 Failed "
+                     "| 🔴 Fallback |")
+        lines.append("|---|---|---|---|")
         suite_rows = []
         for s in suites:
             name = s.get("suite", "").split(".")[-1]
             cat = s.get("category", "")
-            tests = s.get("tests", [])
             counts = defaultdict(int)
-            for t in tests:
-                records = t.get("records", [])
-                has_fallback = any(r.get("offload") == "FALLBACK"
-                                   for r in records)
-                has_offload_data = len(records) > 0
-                last_fb = (records[-1].get("offload") == "FALLBACK") if records else None
-                _, label = classify_test(
-                    t.get("status", "PASSED"), has_fallback, has_offload_data,
-                    last_fb)
-                counts[label] += 1
+            for t in s.get("tests", []):
+                for rec in t.get("records", []):
+                    offload = rec.get("offload", "")
+                    rec_status = rec.get("status", "PASS")
+                    _, label = classify_record(offload, rec_status)
+                    counts[label] += 1
             total = sum(counts.values())
-            po = counts.get("Passed+Offload", 0)
+            po = counts.get("Passed", 0)
             pct = f"{po * 100 / total:.0f}%" if total else "0%"
             suite_rows.append((cat, name, po, pct,
-                               counts.get("Failed+Offload", 0),
-                               counts.get("Passed+Fallback", 0),
-                               counts.get("Failed+Fallback", 0)))
-        for cat, name, po, pct, fo, pfb, ffb in sorted(suite_rows):
-            lines.append(f"| {name} | {po} ({pct}) | {fo} | {pfb} | {ffb} |")
+                               counts.get("Failed", 0),
+                               counts.get("Fallback", 0)))
+        for cat, name, po, pct, fo, pfb in sorted(suite_rows):
+            lines.append(f"| {name} | {po} ({pct}) | {fo} | {pfb} |")
         lines.append("")
 
     # --- Failure Cause Analysis (JSON only) ---
@@ -503,7 +514,7 @@ def format_summary(summary, json_tests, suites=None):
             cause_counts[cause] += 1
 
         lines.append(f"### Failure Cause Analysis "
-                     f"({len(json_failures)} failures from JSON)\n")
+                     f"({len(json_failures)} failures)\n")
         cause_desc = {
             "NO_EXCEPTION": "Velox did not throw expected ANSI exception",
             "WRONG_EXCEPTION": "Exception wrapped as SparkException",
@@ -536,8 +547,8 @@ def format_summary(summary, json_tests, suites=None):
                 xml_suite_counts[short] += 1
                 xml_suite_tests[short].append(f.get("test", ""))
         if xml_suite_counts:
-            lines.append(f"### Failed XML Suites "
-                         f"(not in JSON, {sum(xml_suite_counts.values())} failures)\n")
+            lines.append(f"## Other "
+                         f"({sum(xml_suite_counts.values())} failures)\n")
             lines.append("| Suite | Failures |")
             lines.append("|---|---|")
             for suite, cnt in sorted(xml_suite_counts.items(),
@@ -709,10 +720,10 @@ def _format_generic_table(lines, matrix, suites, key_label):
         lines.append("")
 
 
-def format_full(summary, json_tests, categories, suites=None,
+def format_full(summary, json_records, categories, suites=None,
                 ai_content=None, ai_model=None):
     """Format full report: summary + matrix in <details> + optional AI analysis."""
-    parts = [format_summary(summary, json_tests, suites)]
+    parts = [format_summary(summary, json_records, suites)]
     if ai_content:
         parts.append("")
         parts.append("<details>")
@@ -723,7 +734,7 @@ def format_full(summary, json_tests, categories, suites=None,
     return "\n".join(parts)
 
 
-def format_json_output(summary, json_tests, xml_tests, categories):
+def format_json_output(summary, json_records, xml_tests, categories):
     """Format analysis results as JSON."""
     output = {
         "summary": summary,
@@ -773,7 +784,7 @@ def _build_ai_context(summary, categories):
                     if k not in ("Passed (no data)", "Skipped")}
 
     output = {
-        "json_test_count": summary["json_test_count"],
+        "json_record_count": summary["json_record_count"],
         "by_color": json_colors,
         "failure_count": len(summary["failures"]),
         "failures": compact_failures,


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org


(gluten) 07/07: Cleanup: remove dead analyze-ansi-results.py, drop --mode from workflow

Posted by ch...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a commit to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit 34738660eb590bbd1f98d86c1453a8fad8ae3a4f
Author: Chang chen <ch...@apache.org>
AuthorDate: Tue Apr 21 09:59:32 2026 +0800

    Cleanup: remove dead analyze-ansi-results.py, drop --mode from workflow
    
    - Delete analyze-ansi-results.py (unreferenced, superseded by analyze-ansi.py)
    - Remove --mode full from workflow YAML (argument removed from script)
    - Major simplification of analyze-ansi.py: remove matrix analysis, --mode
      parameter, translate to English, add AI disclaimer
    
    Co-Authored-By: Claude Opus 4 <no...@anthropic.com>
---
 .github/scripts/analyze-ansi-results.py  | 722 -------------------------------
 .github/scripts/analyze-ansi.py          | 382 ++--------------
 .github/workflows/velox_backend_ansi.yml |   2 -
 3 files changed, 35 insertions(+), 1071 deletions(-)

diff --git a/.github/scripts/analyze-ansi-results.py b/.github/scripts/analyze-ansi-results.py
deleted file mode 100644
index 4a17d96121..0000000000
--- a/.github/scripts/analyze-ansi-results.py
+++ /dev/null
@@ -1,722 +0,0 @@
-#!/usr/bin/env python3
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements.  See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License.  You may obtain a copy of the License at
-#
-#    http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Analyze ANSI mode test results from surefire XML and/or test logs.
-
-Supports two input formats:
-  --format xml  : Parse surefire XML reports (CI artifacts)
-  --format log  : Parse test log files (local verify-ansi-expressions.sh output)
-
-Both formats are merged when available: XML provides authoritative pass/fail/skip,
-logs provide expression-level offload/fallback data from EXPRESSION_OFFLOAD_SUMMARY blocks.
-
-Three-color classification:
-  🟢 Passed + Offload  — test passes natively in Velox ANSI mode
-  🟡 Failed + Offload  — test runs in Velox but fails (needs ANSI fix)
-  🔴 Passed + Fallback — test passes but fell back to Spark (Velox can't handle it)
-
-Options:
-  --ai           Call GitHub Models API for analysis
-  --pr-comment   Post report as PR comment
-  --report-dir   Directory containing surefire XML reports (default: ./test-reports/)
-  --log-dir      Directory containing test log files
-  --log          Single log file to parse
-
-Environment variables:
-  GH_TOKEN       — GitHub token for PR comments and GitHub Models API
-  AI_MODEL       — Model name for GitHub Models API (default: gpt-4o)
-  PR_NUMBER      — PR number to comment on
-  TRIGGERED_BY   — GitHub user who triggered the analysis
-  RUN_ID         — GitHub Actions run ID
-"""
-import argparse
-import glob
-import json
-import os
-import re
-import subprocess
-import sys
-import xml.etree.ElementTree as ET
-from collections import defaultdict, OrderedDict
-from pathlib import Path
-
-AI_ENDPOINT = "https://models.inference.ai.azure.com/chat/completions"
-ANSI_RE = re.compile(r'\x1b\[[0-9;]*m')
-
-# Log parsing patterns (from analyze-ansi-test-log.py)
-SUITE_RE = re.compile(r'^(Gluten\w+Suite):$')
-OFFLOAD_RE = re.compile(r"^'(.+)' offload to gluten$")
-FALLBACK_RE = re.compile(r"^'(.+)' NOT use gluten$")
-PASSED_RE = re.compile(r'^- (.+?)(?:\s+\(\d+.*\))?$')
-FAILED_RE = re.compile(r'^- (.+?) \*\*\* FAILED \*\*\*(?:\s+\(\d+.*\))?$')
-IGNORED_RE = re.compile(r'^- (.+?) !!! IGNORED !!!$')
-VALIDATION_FAILED_RE = re.compile(r'Validation failed')
-GLUTEN_CHECK_RE = re.compile(r'glutenCheck(?:Expression|ExceptionInExpression)')
-
-NO_EXCEPTION_RE = re.compile(
-    r'Expected exception .+ to be thrown, but no exception was thrown')
-MSG_MISMATCH_RE = re.compile(
-    r"Expected error message containing '(.+?)' but got '(.+?)'")
-WRONG_EXCEPTION_RE = re.compile(
-    r'Expected (\S+) but got (\S+):')
-
-# EXPRESSION_OFFLOAD_SUMMARY markers
-OFFLOAD_SUMMARY_BEGIN = 'EXPRESSION_OFFLOAD_SUMMARY_BEGIN'
-OFFLOAD_SUMMARY_END = 'EXPRESSION_OFFLOAD_SUMMARY_END'
-
-
-# ---------------------------------------------------------------------------
-# Surefire XML parsing
-# ---------------------------------------------------------------------------
-
-def parse_surefire_reports(base_dir):
-    """Parse all surefire XML reports and return structured test results."""
-    results = []
-    xml_files = glob.glob(f"{base_dir}/**/TEST-*.xml", recursive=True)
-    if not xml_files:
-        return results
-
-    for xml_path in xml_files:
-        try:
-            tree = ET.parse(xml_path)
-        except ET.ParseError:
-            continue
-        suite = tree.getroot()
-        suite_name = suite.get("name", Path(xml_path).stem)
-        job_name = _infer_job_name(xml_path)
-
-        for tc in suite.findall("testcase"):
-            test_name = tc.get("name", "unknown")
-            classname = tc.get("classname", suite_name)
-            time_s = float(tc.get("time", "0"))
-
-            failure = tc.find("failure")
-            error = tc.find("error")
-            skipped = tc.find("skipped")
-
-            if skipped is not None:
-                status = "SKIPPED"
-                message = skipped.get("message", "")
-            elif failure is not None:
-                status = "FAILED"
-                message = (failure.get("message") or failure.text or "")[:500]
-            elif error is not None:
-                status = "ERROR"
-                message = (error.get("message") or error.text or "")[:500]
-            else:
-                status = "PASSED"
-                message = ""
-
-            results.append({
-                "suite": classname,
-                "test": test_name,
-                "status": status,
-                "message": message,
-                "time": time_s,
-                "job": job_name,
-            })
-    return results
-
-
-def _infer_job_name(xml_path):
-    parts = Path(xml_path).parts
-    for p in parts:
-        if "spark-test-" in p:
-            return p
-    return "unknown"
-
-
-def _short_job_name(job):
-    """Shorten job name for table display."""
-    job = job.replace("spark-test-", "").replace("-report", "")
-    return job or "unknown"
-
-
-# ---------------------------------------------------------------------------
-# Log file parsing
-# ---------------------------------------------------------------------------
-
-def parse_log(path):
-    """Parse test log and return list of test-level results."""
-    lines = []
-    with open(path, 'r', errors='replace') as f:
-        for raw_line in f:
-            lines.append(ANSI_RE.sub('', raw_line).strip())
-
-    tests = []
-    current_suite = None
-    test_entries = []
-
-    for i, line in enumerate(lines):
-        if not line:
-            continue
-        m = SUITE_RE.match(line)
-        if m:
-            current_suite = m.group(1)
-            continue
-        m = OFFLOAD_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), None))
-            continue
-        m = FALLBACK_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), None))
-            continue
-        m = FAILED_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), 'FAILED'))
-            continue
-        m = IGNORED_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), 'IGNORED'))
-            continue
-        m = PASSED_RE.match(line)
-        if m and not VALIDATION_FAILED_RE.search(line):
-            test_entries.append((i, current_suite, m.group(1), 'PASSED'))
-            continue
-
-    test_map = OrderedDict()
-    for line_idx, suite, name, result in test_entries:
-        key = (suite, name)
-        if key not in test_map:
-            test_map[key] = {
-                'suite': suite or '(unknown)',
-                'test': name,
-                'result': result,
-                'start_line': line_idx,
-            }
-        else:
-            entry = test_map[key]
-            if result is not None:
-                entry['result'] = result
-            entry['start_line'] = min(entry['start_line'], line_idx)
-
-    test_list = list(test_map.values())
-    for i, t in enumerate(test_list):
-        if i + 1 < len(test_list):
-            t['end_line'] = test_list[i + 1]['start_line']
-        else:
-            t['end_line'] = len(lines)
-
-    results = []
-    for t in test_list:
-        if t['result'] == 'IGNORED':
-            has_fallback = False
-            has_velox = False
-            fail_cause = None
-        else:
-            has_fallback = False
-            has_velox = False
-            fail_cause = None
-            for j in range(t['start_line'], t['end_line']):
-                if VALIDATION_FAILED_RE.search(lines[j]):
-                    has_fallback = True
-                if GLUTEN_CHECK_RE.search(lines[j]):
-                    has_velox = True
-                if t['result'] == 'FAILED' and fail_cause is None:
-                    if NO_EXCEPTION_RE.search(lines[j]):
-                        fail_cause = 'NO_EXCEPTION'
-                    elif MSG_MISMATCH_RE.search(lines[j]):
-                        fail_cause = 'MSG_MISMATCH'
-                    elif WRONG_EXCEPTION_RE.search(lines[j]):
-                        fail_cause = 'WRONG_EXCEPTION'
-            if t['result'] == 'FAILED' and fail_cause is None:
-                fail_cause = 'OTHER'
-
-        results.append({
-            'suite': t['suite'],
-            'test': t['test'],
-            'fallback': has_fallback,
-            'velox': has_velox,
-            'result': t['result'] or 'PASSED',
-            'fail_cause': fail_cause,
-        })
-
-    return results
-
-
-# ---------------------------------------------------------------------------
-# EXPRESSION_OFFLOAD_SUMMARY block parsing
-# ---------------------------------------------------------------------------
-
-def parse_offload_summary_from_logs(log_paths):
-    """Parse EXPRESSION_OFFLOAD_SUMMARY blocks from log files.
-
-    Returns dict: {(suite, test_name): [OffloadRecord...]}
-    where each record is {method, expression, meta, offload, status}.
-    """
-    all_records = {}
-
-    for path in log_paths:
-        in_block = False
-        current_suite = None
-        current_test = None
-
-        with open(path, 'r', errors='replace') as f:
-            for raw_line in f:
-                line = ANSI_RE.sub('', raw_line).strip()
-                # Strip log4j prefix if present
-                if '] ' in line:
-                    line = line[line.rindex('] ') + 2:]
-                # Strip SLF4J/logback prefix: "HH:MM:SS.mmm WARN classname: content"
-                m = re.match(
-                    r'\d{2}:\d{2}:\d{2}\.\d+ \w+ [\w.$]+:\s*(.*)', line)
-                if m:
-                    line = m.group(1)
-
-                if OFFLOAD_SUMMARY_BEGIN in line:
-                    in_block = True
-                    continue
-                if OFFLOAD_SUMMARY_END in line:
-                    in_block = False
-                    current_suite = None
-                    current_test = None
-                    continue
-                if not in_block:
-                    continue
-
-                stripped = line.strip()
-                if stripped.endswith(':') and not stripped.startswith(('N|', 'E|')):
-                    if '|' not in stripped:
-                        name = stripped[:-1].strip()
-                        if current_suite is None:
-                            current_suite = name
-                        else:
-                            current_test = name
-                    continue
-
-                if '|' in stripped and stripped[0] in ('N', 'E'):
-                    parts = stripped.split('|')
-                    if len(parts) >= 5:
-                        record = {
-                            'method': 'checkException' if parts[0] == 'E' else 'checkExpression',
-                            'expression': parts[1],
-                            'meta': parts[2],
-                            'offload': parts[3],
-                            'status': parts[4],
-                        }
-                        key = (current_suite, current_test)
-                        all_records.setdefault(key, []).append(record)
-
-    return all_records
-
-
-# ---------------------------------------------------------------------------
-# Classification
-# ---------------------------------------------------------------------------
-
-def classify_test(status, has_fallback, has_offload_data):
-    """Assign three-color classification."""
-    if status == "SKIPPED":
-        return "⚪", "Skipped"
-    if has_fallback:
-        if status == "PASSED":
-            return "🔴", "Passed+Fallback"
-        return "🔴", "Failed+Fallback"
-    if not has_offload_data:
-        if status == "PASSED":
-            return "⚪", "Passed (no data)"
-        return "🟡", "Failed (no data)"
-    if status == "PASSED":
-        return "🟢", "Passed+Offload"
-    if status in ("FAILED", "ERROR"):
-        return "🟡", "Failed+Offload"
-    return "🟡", "Failed"
-
-
-def determine_fallback(test_key, offload_records):
-    """Determine fallback status and whether offload data exists."""
-    records = offload_records.get(test_key, [])
-    if not records:
-        return False, False
-    return any(r['offload'] == 'FALLBACK' for r in records), True
-
-
-def build_summary(results, offload_records=None):
-    """Build summary with three-color classification."""
-    offload_records = offload_records or {}
-    summary = {
-        "total": len(results),
-        "by_color": defaultdict(int),
-        "by_job": defaultdict(lambda: defaultdict(int)),
-        "failures": [],
-    }
-    for t in results:
-        suite = t.get("suite", "")
-        test = t.get("test", "")
-        status = t.get("status", "PASSED")
-
-        has_fallback = t.get("fallback", False)
-        has_offload_data = False
-        if offload_records:
-            test_key = (suite.split('.')[-1], test)
-            fb, has_data = determine_fallback(test_key, offload_records)
-            has_fallback = has_fallback or fb
-            has_offload_data = has_data
-
-        color, label = classify_test(status, has_fallback, has_offload_data)
-        t["color"] = color
-        t["label"] = label
-        t["fallback"] = has_fallback
-        summary["by_color"][label] += 1
-        job = t.get("job", "unknown")
-        summary["by_job"][job][label] += 1
-        if status in ("FAILED", "ERROR"):
-            summary["failures"].append(t)
-    return summary
-
-
-# ---------------------------------------------------------------------------
-# Report generation
-# ---------------------------------------------------------------------------
-
-def format_markdown_report(summary, results, ai_analysis=None):
-    """Generate markdown report."""
-    lines = ["## ANSI Mode Test Analysis Report\n"]
-
-    lines.append("### Overview\n")
-    lines.append(f"Total tests: **{summary['total']}**\n")
-    lines.append("| Classification | Count |")
-    lines.append("|---|---|")
-    for label in ["Passed+Offload", "Failed+Offload", "Passed+Fallback",
-                  "Failed+Fallback", "Failed", "Passed (no data)",
-                  "Failed (no data)", "Skipped"]:
-        count = summary["by_color"].get(label, 0)
-        if count > 0:
-            color = {"Passed+Offload": "🟢", "Failed+Offload": "🟡",
-                     "Passed+Fallback": "🔴", "Failed+Fallback": "🔴",
-                     "Failed": "🟡", "Passed (no data)": "⚪",
-                     "Failed (no data)": "🟡", "Skipped": "⚪"}.get(label, "")
-            lines.append(f"| {color} {label} | {count} |")
-    lines.append("")
-
-    lines.append("### Per-Job Breakdown\n")
-    for job, counts in sorted(summary["by_job"].items()):
-        lines.append(f"**{job}**")
-        for label, count in sorted(counts.items()):
-            lines.append(f"- {label}: {count}")
-        lines.append("")
-
-    if summary["failures"]:
-        lines.append("### Failed Tests (sample, max 50)\n")
-        lines.append("| Suite | Test | Job | Color | Message |")
-        lines.append("|---|---|---|---|---|")
-        for t in summary["failures"][:50]:
-            msg = t.get("message", "")[:200].replace("|", "\\|").replace("\n", " ")
-            job = _short_job_name(t.get("job", ""))
-            lines.append(
-                f"| {t['suite'].split('.')[-1]} | {t['test']} "
-                f"| {job} | {t['color']} {t['label']} | {msg} |")
-        if len(summary["failures"]) > 50:
-            lines.append(f"\n*...and {len(summary['failures']) - 50} more failures*\n")
-        lines.append("")
-
-    if ai_analysis:
-        lines.append("### AI Analysis\n")
-        lines.append(ai_analysis)
-        lines.append("")
-
-    triggered_by = os.environ.get("TRIGGERED_BY", "unknown")
-    run_id = os.environ.get("RUN_ID", "")
-    lines.append(f"\n---\n*Triggered by @{triggered_by} | "
-                 f"[Workflow run](../actions/runs/{run_id})*")
-    return "\n".join(lines)
-
-
-def format_log_table(tests, fallback_only=False, failed_only=False, suite_filter=None):
-    """Print table for log-based analysis (local usage)."""
-    filtered = tests
-    if suite_filter:
-        filtered = [t for t in filtered if suite_filter in t['suite']]
-    if fallback_only:
-        filtered = [t for t in filtered if t['fallback']]
-    if failed_only:
-        filtered = [t for t in filtered if t['result'] == 'FAILED']
-
-    if not filtered:
-        print("No matching tests found.")
-        return
-
-    sw = max(max(len(t['suite']) for t in filtered), len('Suite'))
-    tw = max(max(len(t['test']) for t in filtered), len('Test'))
-
-    def velox_str(t):
-        if t['result'] == 'IGNORED':
-            return 'N/A'
-        return 'yes' if t['velox'] else 'no'
-
-    def fallback_str(t):
-        if t['result'] == 'IGNORED':
-            return 'N/A'
-        return 'found' if t['fallback'] else 'not found'
-
-    def cause_str(t):
-        return t.get('fail_cause') or ''
-
-    has_failures = any(t['result'] == 'FAILED' for t in filtered)
-    if has_failures:
-        cw = max(max((len(cause_str(t)) for t in filtered), default=5), len('Cause'))
-        header = (f"| {'Suite':<{sw}} | {'Test':<{tw}} | Velox | Fallback  "
-                  f"| Result  | {'Cause':<{cw}} |")
-        sep = (f"|{'-' * (sw + 2)}|{'-' * (tw + 2)}|-------|--------"
-               f"---|---------|{'-' * (cw + 2)}|")
-    else:
-        header = f"| {'Suite':<{sw}} | {'Test':<{tw}} | Velox | Fallback  | Result  |"
-        sep = f"|{'-' * (sw + 2)}|{'-' * (tw + 2)}|-------|-----------|---------|"
-    print(header)
-    print(sep)
-    for t in filtered:
-        v = velox_str(t)
-        fb = fallback_str(t)
-        if has_failures:
-            c = cause_str(t)
-            print(f"| {t['suite']:<{sw}} | {t['test']:<{tw}} | {v:<5} | {fb:<9} "
-                  f"| {t['result']:<7} | {c:<{cw}} |")
-        else:
-            print(f"| {t['suite']:<{sw}} | {t['test']:<{tw}} | {v:<5} | {fb:<9} "
-                  f"| {t['result']:<7} |")
-
-    print()
-    total = len(filtered)
-    passed = sum(1 for t in filtered if t['result'] == 'PASSED')
-    failed = sum(1 for t in filtered if t['result'] == 'FAILED')
-    ignored = sum(1 for t in filtered if t['result'] == 'IGNORED')
-    velox_yes = sum(1 for t in filtered if t.get('velox'))
-    velox_no = sum(1 for t in filtered if not t.get('velox') and t['result'] != 'IGNORED')
-    fb_found = sum(1 for t in filtered if t['fallback'])
-    print(f"Total: {total} | Velox: {velox_yes} | No Velox: {velox_no} | "
-          f"Fallback: {fb_found}")
-    print(f"Passed: {passed} | Failed: {failed} | Ignored: {ignored}")
-
-    if failed > 0:
-        causes = {}
-        for t in filtered:
-            c = t.get('fail_cause')
-            if c:
-                causes[c] = causes.get(c, 0) + 1
-        cause_parts = [f"{c}: {n}" for c, n in sorted(causes.items())]
-        print(f"Failure causes: {' | '.join(cause_parts)}")
-
-    print()
-    print("Per-suite summary:")
-    suites = OrderedDict()
-    for t in filtered:
-        s = t['suite']
-        if s not in suites:
-            suites[s] = {'total': 0, 'velox': 0, 'no_velox': 0, 'fb_found': 0,
-                         'passed': 0, 'failed': 0, 'ignored': 0}
-        suites[s]['total'] += 1
-        if t.get('velox'):
-            suites[s]['velox'] += 1
-        elif t['result'] != 'IGNORED':
-            suites[s]['no_velox'] += 1
-        if t['fallback']:
-            suites[s]['fb_found'] += 1
-        suites[s][t['result'].lower()] += 1
-
-    sn_w = max(len(s) for s in suites)
-    print(f"| {'Suite':<{sn_w}} | Total | Velox | No Velox | Fallback "
-          f"| Passed | Failed | Ignored |")
-    print(f"|{'-' * (sn_w + 2)}|-------|-------|----------|----------|"
-          f"--------|--------|---------|")
-    for s, c in suites.items():
-        print(f"| {s:<{sn_w}} | {c['total']:>5} | {c['velox']:>5} | "
-              f"{c['no_velox']:>8} | {c['fb_found']:>8} | {c['passed']:>6} | "
-              f"{c['failed']:>6} | {c['ignored']:>7} |")
-
-
-# ---------------------------------------------------------------------------
-# AI analysis
-# ---------------------------------------------------------------------------
-
-def call_github_models_api(summary, failures_sample):
-    """Call GitHub Models API for AI analysis."""
-    token = os.environ.get("GH_TOKEN")
-    model = os.environ.get("AI_MODEL", "gpt-4o")
-    if not token:
-        return None
-
-    failure_text = "\n".join(
-        f"- {t['suite'].split('.')[-1]}.{t['test']}: {t['color']} {t['label']} — "
-        f"{t.get('message', '')[:200]}"
-        for t in failures_sample[:30]
-    )
-
-    prompt = f"""Analyze these ANSI SQL mode test results from Apache Gluten (Velox backend).
-
-Summary:
-- Total tests: {summary['total']}
-- 🟢 Passed+Offload (native Velox ANSI): {summary['by_color'].get('Passed+Offload', 0)}
-- 🟡 Failed+Offload (Velox ran but failed): {summary['by_color'].get('Failed+Offload', 0)}
-- 🔴 Passed+Fallback (fell back to Spark): {summary['by_color'].get('Passed+Fallback', 0)}
-
-Sample failures:
-{failure_text}
-
-Provide a brief analysis (under 500 words):
-1. Key failure patterns and root causes
-2. Which expression types need ANSI implementation work
-3. Priority recommendations for fixing"""
-
-    try:
-        import requests
-        resp = requests.post(
-            AI_ENDPOINT,
-            headers={
-                "Authorization": f"Bearer {token}",
-                "Content-Type": "application/json",
-            },
-            json={
-                "model": model,
-                "messages": [{"role": "user", "content": prompt}],
-                "max_tokens": 1000,
-            },
-            timeout=60,
-        )
-        if resp.status_code == 200:
-            return resp.json()["choices"][0]["message"]["content"]
-        else:
-            return (f"*AI analysis unavailable (HTTP {resp.status_code}). "
-                    f"The commenter may not have GitHub Models API access.*")
-    except Exception as e:
-        return f"*AI analysis unavailable: {e}*"
-
-
-# ---------------------------------------------------------------------------
-# Output helpers
-# ---------------------------------------------------------------------------
-
-def post_pr_comment(markdown):
-    pr_number = os.environ.get("PR_NUMBER")
-    if not pr_number:
-        print("PR_NUMBER not set, skipping PR comment")
-        return
-    try:
-        subprocess.run(
-            ["gh", "pr", "comment", pr_number, "--body", markdown],
-            check=True, timeout=30,
-        )
-        print(f"Posted comment to PR #{pr_number}")
-    except (subprocess.CalledProcessError, subprocess.TimeoutExpired,
-            FileNotFoundError) as e:
-        print(f"Failed to post PR comment: {e}")
-
-
-def write_job_summary(markdown):
-    summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
-    if summary_path:
-        with open(summary_path, "a") as f:
-            f.write(markdown)
-        print("Wrote Job Summary")
-
-
-# ---------------------------------------------------------------------------
-# Main
-# ---------------------------------------------------------------------------
-
-def main():
-    parser = argparse.ArgumentParser(
-        description='Analyze Gluten ANSI mode test results')
-    parser.add_argument('--format', choices=['xml', 'log'], default='xml',
-                        help='Input format: xml (surefire reports) or log (test logs)')
-    parser.add_argument('--report-dir', default='./test-reports/',
-                        help='Directory with surefire XML reports')
-    parser.add_argument('--log-dir', default=None,
-                        help='Directory with test log files')
-    parser.add_argument('--log', default=None,
-                        help='Single log file to parse')
-    parser.add_argument('--ai', action='store_true',
-                        help='Call GitHub Models API for analysis')
-    parser.add_argument('--pr-comment', action='store_true',
-                        help='Post report as PR comment')
-    parser.add_argument('--fallback-only', action='store_true',
-                        help='Show only tests that fell back to Spark (log mode)')
-    parser.add_argument('--failed-only', action='store_true',
-                        help='Show only failed tests (log mode)')
-    parser.add_argument('--suite', type=str, default=None,
-                        help='Filter by suite name (log mode)')
-    args = parser.parse_args()
-
-    offload_records = {}
-
-    if args.format == 'log':
-        # Log-based analysis (local mode)
-        log_path = args.log
-        if not log_path:
-            print("--log is required for --format log")
-            sys.exit(1)
-        tests = parse_log(log_path)
-        if not tests:
-            print(f"No tests found in {log_path}")
-            sys.exit(1)
-
-        offload_records = parse_offload_summary_from_logs([log_path])
-
-        for t in tests:
-            key = (t['suite'], t['test'])
-            records = offload_records.get(key, [])
-            if records:
-                t['fallback'] = any(r['offload'] == 'FALLBACK' for r in records)
-                t['velox'] = any(r['offload'] == 'OFFLOAD' for r in records)
-
-        format_log_table(tests, fallback_only=args.fallback_only,
-                         failed_only=args.failed_only, suite_filter=args.suite)
-        return
-
-    # XML-based analysis (CI mode)
-    results = parse_surefire_reports(args.report_dir)
-
-    # Parse offload summary from log files if available
-    log_paths = []
-    if args.log_dir:
-        log_paths = glob.glob(f"{args.log_dir}/**/*.log", recursive=True)
-        log_paths += glob.glob(f"{args.log_dir}/**/*.txt", recursive=True)
-    if args.log:
-        log_paths.append(args.log)
-    if log_paths:
-        offload_records = parse_offload_summary_from_logs(log_paths)
-
-    if not results:
-        msg = ("## ANSI Mode Test Analysis\n\nNo test reports found. "
-               "Build may have failed — check individual job logs.")
-        if args.pr_comment:
-            post_pr_comment(msg)
-        write_job_summary(msg)
-        print("No surefire reports found")
-        sys.exit(0)
-
-    summary = build_summary(results, offload_records)
-
-    ai_analysis = None
-    if args.ai:
-        ai_analysis = call_github_models_api(summary, summary["failures"])
-
-    report = format_markdown_report(summary, results, ai_analysis)
-
-    if args.pr_comment:
-        post_pr_comment(report)
-    else:
-        print(report)
-    write_job_summary(report)
-
-    print(f"Analysis complete: {summary['total']} tests, "
-          f"{len(summary['failures'])} failures")
-    if offload_records:
-        print(f"Offload records parsed from {len(log_paths)} log file(s), "
-              f"{len(offload_records)} test entries")
-
-
-if __name__ == "__main__":
-    main()
diff --git a/.github/scripts/analyze-ansi.py b/.github/scripts/analyze-ansi.py
index 98c3d91633..c03bb0f62d 100644
--- a/.github/scripts/analyze-ansi.py
+++ b/.github/scripts/analyze-ansi.py
@@ -13,18 +13,12 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-"""Unified ANSI mode test analyzer.
+"""ANSI mode test analyzer for Gluten CI.
 
 Data sources:
   --json-dir     JSON files from GlutenExpressionOffloadTracker (expression-level)
   --report-dir   Surefire XML reports (test-method-level, for backends-velox)
 
-Output modes:
-  --mode summary   Test-level three-color classification + failure list
-  --mode matrix    Expression-level matrix by category
-  --mode full      summary + matrix (matrix in <details> fold)
-  --mode json      Structured JSON output for tool consumption
-
 Output targets:
   stdout (default), --pr-comment, --job-summary, --output-file FILE
 """
@@ -122,16 +116,12 @@ def _extract_short_message(message):
     return message.split("\n")[0][:120]
 
 
-
 # ===========================================================================
 # DATA LAYER
 # ===========================================================================
 
 def load_json_data(json_dir):
-    """Load all JSON files from Tracker output directory.
-
-    Returns list of suite dicts: {suite, category, tests: [{name, status, records}]}
-    """
+    """Load all JSON files from Tracker output directory."""
     suites = []
     if not json_dir or not os.path.isdir(json_dir):
         return suites
@@ -146,10 +136,7 @@ def load_json_data(json_dir):
 
 
 def load_surefire_xml(report_dir):
-    """Load surefire XML reports for backends-velox test results.
-
-    Returns list of test dicts: {suite, test, status, message, job}
-    """
+    """Load surefire XML reports for backends-velox test results."""
     results = []
     if not report_dir or not os.path.isdir(report_dir):
         return results
@@ -202,11 +189,7 @@ def _infer_job_name(xml_path):
 # ===========================================================================
 
 def classify_record(offload_status, record_status):
-    """Classify a single record (expression-level).
-
-    offload_status: "OFFLOAD" or "FALLBACK"
-    record_status: "PASS" or "FAIL"
-    """
+    """Classify a single record (expression-level)."""
     is_pass = record_status in ("PASSED", "PASS")
     is_fallback = offload_status == "FALLBACK"
     if is_fallback:
@@ -309,7 +292,6 @@ def build_summary(json_records, xml_tests):
                 "source": "xml",
             })
 
-    # Count unique tests from JSON for the header
     json_test_names = set()
     for r in json_records:
         json_test_names.add((r["suite"], r["test"]))
@@ -324,113 +306,6 @@ def build_summary(json_records, xml_tests):
     }
 
 
-# ---------------------------------------------------------------------------
-# Expression-level matrix analysis
-# ---------------------------------------------------------------------------
-
-def _normalize_type(t):
-    simple = {
-        "boolean": "Boolean", "byte": "TinyInt", "short": "SmallInt",
-        "int": "Int", "bigint": "BigInt", "float": "Float",
-        "double": "Double", "string": "String", "binary": "Binary",
-        "date": "Date", "timestamp": "Timestamp", "timestamp_ntz": "TimestampNTZ",
-        "void": "Null",
-    }
-    low = t.lower().strip()
-    if low in simple:
-        return simple[low]
-    if low.startswith("decimal"):
-        return t.replace("decimal", "Decimal")
-    if low.startswith("array"):
-        return "Array\\<" + _normalize_type(t[6:-1]) + "\\>"
-    if low.startswith("map"):
-        inner = t[4:-1]
-        parts = inner.split(",", 1)
-        if len(parts) == 2:
-            return "Map\\<" + _normalize_type(parts[0]) + "," + _normalize_type(parts[1]) + "\\>"
-    return t.replace("<", "\\<").replace(">", "\\>")
-
-
-def _cell_symbol(offload, status):
-    if offload == "FALLBACK":
-        return "🔴"
-    if status == "PASS":
-        return "🟢"
-    return "🟡"
-
-
-def analyze_expression_matrix(suites):
-    """Build expression-level matrices grouped by category.
-
-    Returns dict: {category: {info, entries, matrix_data}}
-    """
-    categories = defaultdict(lambda: {"entries": [], "suites": set(),
-                                       "tests_pass": 0, "tests_fail": 0,
-                                       "tests_skip": 0})
-
-    for suite_data in suites:
-        cat = suite_data.get("category", "unknown")
-        suite_name = suite_data.get("suite", "")
-        cat_data = categories[cat]
-        cat_data["suites"].add(suite_name)
-
-        for t in suite_data.get("tests", []):
-            if t.get("status") == "PASS":
-                cat_data["tests_pass"] += 1
-            elif t.get("status") == "FAIL":
-                cat_data["tests_fail"] += 1
-            else:
-                cat_data["tests_skip"] += 1
-
-            for rec in t.get("records", []):
-                meta = rec.get("meta", {})
-                fail_cause = rec.get("failCause")
-                fail_type = classify_fail_cause(fail_cause) if fail_cause else None
-                cat_data["entries"].append({
-                    "suite": suite_name,
-                    "test": t["name"],
-                    "method": rec.get("method", "N"),
-                    "expression": rec.get("expression", ""),
-                    "meta": meta,
-                    "offload": rec.get("offload", ""),
-                    "status": rec.get("status", "PASS"),
-                    "fail_cause": fail_cause,
-                    "fail_type": fail_type,
-                })
-
-    return dict(categories)
-
-
-def _build_cast_matrix(entries, suites):
-    """Build cast matrix: (fromType, toType) -> {suite: symbol}."""
-    matrix = defaultdict(lambda: defaultdict(lambda: "⚪"))
-    for e in entries:
-        from_t = _normalize_type(e["meta"].get("fromType", "?"))
-        to_t = _normalize_type(e["meta"].get("toType", "?"))
-        key = (from_t, to_t)
-        sym = _cell_symbol(e["offload"], e["status"])
-        cur = matrix[key].get(e["suite"], "⚪")
-        matrix[key][e["suite"]] = _worse(sym, cur)
-    return matrix
-
-
-def _build_keyed_matrix(entries, suites, meta_key):
-    matrix = defaultdict(lambda: defaultdict(lambda: "⚪"))
-    for e in entries:
-        key = e["meta"].get(meta_key, "?")
-        sym = _cell_symbol(e["offload"], e["status"])
-        cur = matrix[key].get(e["suite"], "⚪")
-        matrix[key][e["suite"]] = _worse(sym, cur)
-    return matrix
-
-
-_PRIORITY = {"🟡": 3, "🔴": 2, "🟢": 1, "⚪": 0}
-
-
-def _worse(a, b):
-    return a if _PRIORITY.get(a, 0) >= _PRIORITY.get(b, 0) else b
-
-
 # ===========================================================================
 # OUTPUT LAYER
 # ===========================================================================
@@ -454,10 +329,8 @@ def format_summary(summary, json_records, suites=None):
                  f"{json_record_count} records** | "
                  f"**Other suites: {xml_total} tests**\n")
 
-    # --- ANSI Offload section ---
     lines.append("## ANSI Offload\n")
 
-    # --- Overview: record-level stats ---
     lines.append("### Overview (ANSI Offload Expression Records)\n")
     lines.append("| Classification | Count | % |")
     lines.append("|---|---|---|")
@@ -472,7 +345,6 @@ def format_summary(summary, json_records, suites=None):
             lines.append(f"| {color} {label} | {count} | {pct:.1f}% |")
     lines.append("")
 
-    # --- Per-Suite Summary (record-level) ---
     if suites:
         lines.append("### Per-Suite Summary\n")
         lines.append("| Suite | 🟢 Passed | 🟡 Failed "
@@ -499,7 +371,6 @@ def format_summary(summary, json_records, suites=None):
             lines.append(f"| {name} | {po} ({pct}) | {fo} | {pfb} |")
         lines.append("")
 
-    # --- Failure Cause Analysis (JSON only) ---
     json_failures = [f for f in summary["failures"] if f.get("source") == "json"]
     xml_failures = [f for f in summary["failures"] if f.get("source") == "xml"]
 
@@ -527,7 +398,6 @@ def format_summary(summary, json_records, suites=None):
                              f"| {cause_desc.get(cause, '')} |")
         lines.append("")
 
-    # --- XML: failed suite summary (exclude suites already in JSON) ---
     if xml_failures:
         json_suite_names = set()
         if suites:
@@ -559,166 +429,9 @@ def format_summary(summary, json_records, suites=None):
     return "\n".join(lines)
 
 
-def format_matrix(categories):
-    """Format expression-level matrix as markdown."""
-    lines = ["## Expression Offload Matrix\n"]
-
-    cat_order = ["cast", "arithmetic", "collection", "datetime",
-                 "math", "decimal", "string", "aggregate", "errors"]
-
-    for cat in cat_order:
-        if cat not in categories:
-            continue
-        data = categories[cat]
-        total = data["tests_pass"] + data["tests_fail"] + data["tests_skip"]
-        lines.append(
-            f"### {cat.title()} "
-            f"({total} tests: {data['tests_pass']} passed, "
-            f"{data['tests_fail']} failed, {data['tests_skip']} skipped)\n")
-
-        suites = sorted(data["suites"])
-        entries = data["entries"]
-
-        if not entries:
-            lines.append("*No expression-level data for this category.*\n")
-            continue
-
-        if cat == "cast":
-            matrix = _build_cast_matrix(entries, suites)
-            _format_cast_tables(lines, matrix, suites)
-        elif cat == "arithmetic":
-            matrix = _build_keyed_matrix(entries, suites, "operator")
-            _format_generic_table(lines, matrix, suites, "Operator")
-        else:
-            matrix = _build_keyed_matrix(entries, suites, "expr")
-            _format_generic_table(lines, matrix, suites, "Expression")
-
-        lines.append("")
-
-    # Coverage table
-    lines.append("### Coverage Summary\n")
-    lines.append("| Category | Tests | Passed | Failed | Skipped |")
-    lines.append("|---|---|---|---|---|")
-    t_total = t_pass = t_fail = t_skip = 0
-    for cat in cat_order:
-        if cat not in categories:
-            continue
-        d = categories[cat]
-        total = d["tests_pass"] + d["tests_fail"] + d["tests_skip"]
-        lines.append(
-            f"| {cat} | {total} | {d['tests_pass']} | "
-            f"{d['tests_fail']} | {d['tests_skip']} |")
-        t_total += total
-        t_pass += d["tests_pass"]
-        t_fail += d["tests_fail"]
-        t_skip += d["tests_skip"]
-    lines.append(
-        f"| **Total** | **{t_total}** | **{t_pass}** | "
-        f"**{t_fail}** | **{t_skip}** |")
-    if t_total > 0:
-        pct = t_pass * 100 / t_total
-        lines.append(f"\nPass rate: {t_pass}/{t_total} ({pct:.1f}%)\n")
-
-    return "\n".join(lines)
-
-
-def _format_cast_tables(lines, matrix, suites):
-    """Format cast matrix split into fallback/pass/fail groups."""
-    fallback_rows = []
-    pass_rows = []
-    fail_rows = []
-
-    for (from_t, to_t), suite_map in sorted(matrix.items()):
-        merged = "⚪"
-        for s in suites:
-            merged = _worse(merged, suite_map.get(s, "⚪"))
-
-        if merged == "🔴":
-            fallback_rows.append((from_t, to_t, suite_map))
-        elif merged == "🟢":
-            pass_rows.append((from_t, to_t, suite_map))
-        else:
-            fail_rows.append((from_t, to_t, suite_map))
-
-    suite_headers = " | ".join(s.replace("Gluten", "") for s in suites)
-
-    if fallback_rows:
-        lines.append(f"**🔴 Fallback ({len(fallback_rows)} type pairs)**\n")
-        lines.append(f"| From | To | {suite_headers} |")
-        lines.append("|---|---| " + " | ".join(["---"] * len(suites)) + " |")
-        for from_t, to_t, sm in fallback_rows:
-            cells = " | ".join(sm.get(s, "⚪") for s in suites)
-            lines.append(f"| {from_t} | {to_t} | {cells} |")
-        lines.append("")
-
-    if pass_rows:
-        lines.append(f"**🟢 Passed ({len(pass_rows)} type pairs)**\n")
-        by_from = defaultdict(list)
-        for from_t, to_t, _ in pass_rows:
-            by_from[from_t].append(to_t)
-        for from_t in sorted(by_from):
-            tos = ", ".join(sorted(by_from[from_t]))
-            lines.append(f"- {from_t} → {tos}")
-        lines.append("")
-
-    if fail_rows:
-        lines.append(f"**🟡 Failed ({len(fail_rows)} type pairs)**\n")
-        lines.append(f"| From | To | {suite_headers} |")
-        lines.append("|---|---| " + " | ".join(["---"] * len(suites)) + " |")
-        for from_t, to_t, sm in fail_rows:
-            cells = " | ".join(sm.get(s, "⚪") for s in suites)
-            lines.append(f"| {from_t} | {to_t} | {cells} |")
-        lines.append("")
-
-
-def _format_generic_table(lines, matrix, suites, key_label):
-    """Format a generic matrix table split into fallback/pass/fail groups."""
-    fallback_rows = []
-    pass_rows = []
-    fail_rows = []
-
-    for key, suite_map in sorted(matrix.items()):
-        merged = "⚪"
-        for s in suites:
-            merged = _worse(merged, suite_map.get(s, "⚪"))
-
-        if merged == "🔴":
-            fallback_rows.append((key, suite_map))
-        elif merged == "🟢":
-            pass_rows.append((key, suite_map))
-        else:
-            fail_rows.append((key, suite_map))
-
-    suite_headers = " | ".join(s.replace("Gluten", "") for s in suites)
-
-    if fallback_rows:
-        lines.append(f"**🔴 Fallback ({len(fallback_rows)})**\n")
-        lines.append(f"| {key_label} | {suite_headers} |")
-        lines.append("|---| " + " | ".join(["---"] * len(suites)) + " |")
-        for key, sm in fallback_rows:
-            cells = " | ".join(sm.get(s, "⚪") for s in suites)
-            lines.append(f"| {key} | {cells} |")
-        lines.append("")
-
-    if pass_rows:
-        lines.append(f"**🟢 Passed ({len(pass_rows)})**\n")
-        for key, _ in pass_rows:
-            lines.append(f"- {key}")
-        lines.append("")
-
-    if fail_rows:
-        lines.append(f"**🟡 Failed ({len(fail_rows)})**\n")
-        lines.append(f"| {key_label} | {suite_headers} |")
-        lines.append("|---| " + " | ".join(["---"] * len(suites)) + " |")
-        for key, sm in fail_rows:
-            cells = " | ".join(sm.get(s, "⚪") for s in suites)
-            lines.append(f"| {key} | {cells} |")
-        lines.append("")
-
-
-def format_full(summary, json_records, categories, suites=None,
-                ai_content=None, ai_model=None):
-    """Format full report: summary + matrix in <details> + optional AI analysis."""
+def format_report(summary, json_records, suites=None,
+                  ai_content=None, ai_model=None):
+    """Format full report: summary + optional AI analysis."""
     parts = [format_summary(summary, json_records, suites)]
     if ai_content:
         parts.append("")
@@ -732,23 +445,6 @@ def format_full(summary, json_records, categories, suites=None,
     return "\n".join(parts)
 
 
-def format_json_output(summary, json_records, xml_tests, categories):
-    """Format analysis results as JSON."""
-    output = {
-        "summary": summary,
-        "categories": {},
-    }
-    for cat, data in categories.items():
-        output["categories"][cat] = {
-            "tests_pass": data["tests_pass"],
-            "tests_fail": data["tests_fail"],
-            "tests_skip": data["tests_skip"],
-            "suites": sorted(data["suites"]),
-            "entry_count": len(data["entries"]),
-        }
-    return json.dumps(output, indent=2, ensure_ascii=False)
-
-
 # ---------------------------------------------------------------------------
 # AI analysis via GitHub Models API
 # ---------------------------------------------------------------------------
@@ -756,8 +452,8 @@ def format_json_output(summary, json_records, xml_tests, categories):
 GITHUB_MODELS_API = "https://models.inference.ai.azure.com/chat/completions"
 
 
-def _build_ai_context(summary, categories):
-    """Build a compact JSON context for AI analysis (fits within 16K token limit)."""
+def _build_ai_context(summary, suites):
+    """Build a compact JSON context for AI analysis."""
     compact_failures = []
     for f in summary["failures"][:100]:
         cause = classify_fail_cause(f.get("message", ""))
@@ -770,13 +466,16 @@ def _build_ai_context(summary, categories):
             "message": short_msg[:120],
         })
 
-    compact_cats = {}
-    for cat, data in categories.items():
-        compact_cats[cat] = {
-            "tests_pass": data["tests_pass"],
-            "tests_fail": data["tests_fail"],
-            "suites": sorted(data["suites"]),
-        }
+    compact_cats = defaultdict(lambda: {"tests_pass": 0, "tests_fail": 0,
+                                         "suites": set()})
+    for s in suites:
+        cat = s.get("category", "unknown")
+        compact_cats[cat]["suites"].add(s.get("suite", ""))
+        for t in s.get("tests", []):
+            if t.get("status") in ("PASS", "PASSED"):
+                compact_cats[cat]["tests_pass"] += 1
+            elif t.get("status") in ("FAIL", "FAILED", "ERROR"):
+                compact_cats[cat]["tests_fail"] += 1
 
     json_colors = {k: v for k, v in summary["by_color"].items()
                     if k not in ("Passed (no data)", "Skipped")}
@@ -786,16 +485,16 @@ def _build_ai_context(summary, categories):
         "by_color": json_colors,
         "failure_count": len(summary["failures"]),
         "failures": compact_failures,
-        "categories": compact_cats,
+        "categories": {cat: {"tests_pass": d["tests_pass"],
+                              "tests_fail": d["tests_fail"],
+                              "suites": sorted(d["suites"])}
+                        for cat, d in compact_cats.items()},
     }
     return json.dumps(output, indent=2, ensure_ascii=False)
 
 
 def call_ai_analysis(json_output, model=None):
-    """Call GitHub Models API for deep analysis with fallback chain.
-
-    Returns (content, model_used) or (None, None) on failure.
-    """
+    """Call GitHub Models API for deep analysis with fallback chain."""
     import requests
 
     token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
@@ -878,11 +577,9 @@ def write_job_summary(report):
 # ===========================================================================
 
 def main():
-    parser = argparse.ArgumentParser(description="Unified ANSI test analyzer")
+    parser = argparse.ArgumentParser(description="ANSI mode test analyzer")
     parser.add_argument("--json-dir", help="JSON directory from Tracker")
     parser.add_argument("--report-dir", help="Surefire XML directory")
-    parser.add_argument("--mode", choices=["summary", "matrix", "full", "json"],
-                        default="full")
     parser.add_argument("--pr-comment", action="store_true")
     parser.add_argument("--job-summary", action="store_true")
     parser.add_argument("--output-file", help="Write output to file")
@@ -898,25 +595,16 @@ def main():
     json_records = analyze_json_tests(suites)
     xml_tests = analyze_xml_tests(xml_results)
     summary = build_summary(json_records, xml_tests)
-    categories = analyze_expression_matrix(suites)
-
-    if args.mode == "summary":
-        report = format_summary(summary, json_records, suites)
-    elif args.mode == "matrix":
-        report = format_matrix(categories)
-    elif args.mode == "full":
-        ai_content, ai_model = None, None
-        if args.ai_analysis:
-            ai_context = _build_ai_context(summary, categories)
-            model = args.ai_model or os.environ.get("AI_MODEL", "")
-            ai_content, ai_model = call_ai_analysis(
-                ai_context, model or None)
-        report = format_full(summary, json_records, categories, suites,
-                             ai_content=ai_content, ai_model=ai_model)
-    elif args.mode == "json":
-        report = format_json_output(summary, json_records, xml_tests, categories)
-
-    # Output
+
+    ai_content, ai_model = None, None
+    if args.ai_analysis:
+        ai_context = _build_ai_context(summary, suites)
+        model = args.ai_model or os.environ.get("AI_MODEL", "")
+        ai_content, ai_model = call_ai_analysis(ai_context, model or None)
+
+    report = format_report(summary, json_records, suites,
+                           ai_content=ai_content, ai_model=ai_model)
+
     if args.output_file:
         with open(args.output_file, "w") as f:
             f.write(report)
diff --git a/.github/workflows/velox_backend_ansi.yml b/.github/workflows/velox_backend_ansi.yml
index 0cddf230f1..321b95459d 100644
--- a/.github/workflows/velox_backend_ansi.yml
+++ b/.github/workflows/velox_backend_ansi.yml
@@ -513,7 +513,6 @@ jobs:
           python3 .github/scripts/analyze-ansi.py \
             --json-dir ./ansi-offload/ \
             --report-dir ./test-reports/ \
-            --mode full \
             --ai-analysis \
             --ai-model "${AI_MODEL}" \
             --pr-comment
@@ -603,7 +602,6 @@ jobs:
           python3 .github/scripts/analyze-ansi.py \
             --json-dir ./ansi-offload/ \
             --report-dir ./test-reports/ \
-            --mode full \
             --ai-analysis \
             --ai-model "${AI_MODEL}" \
             --pr-comment


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org


(gluten) 02/07: Fix classify_test: use last record's offload status for failed tests

Posted by ch...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a commit to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit 3fde6ba469072ab816924fcb6cdad6a6aaeeb5a9
Author: Chang chen <ch...@apache.org>
AuthorDate: Tue Apr 21 08:34:03 2026 +0800

    Fix classify_test: use last record's offload status for failed tests
    
    For failed tests, failure always occurs at the last record. The previous
    logic used any(FALLBACK) across all records, misclassifying tests where
    intermediate records were FALLBACK but the failing last record was OFFLOAD.
    
    Co-Authored-By: Claude Opus 4 <no...@anthropic.com>
---
 .github/scripts/analyze-ansi.py | 29 +++++++++++++++++++----------
 1 file changed, 19 insertions(+), 10 deletions(-)

diff --git a/.github/scripts/analyze-ansi.py b/.github/scripts/analyze-ansi.py
index d8d032d014..26f4200e2d 100644
--- a/.github/scripts/analyze-ansi.py
+++ b/.github/scripts/analyze-ansi.py
@@ -205,24 +205,29 @@ def _infer_job_name(xml_path):
 # ANALYSIS LAYER
 # ===========================================================================
 
-def classify_test(status, has_fallback, has_offload_data):
-    """Unified three-color classification."""
+def classify_test(status, has_fallback, has_offload_data, last_record_fallback=None):
+    """Unified three-color classification.
+
+    For failed tests, last_record_fallback (bool) determines Offload vs Fallback
+    because failure always occurs at the last record.
+    """
     is_pass = status in ("PASSED", "PASS")
     is_skip = status in ("SKIPPED", "SKIP")
+    is_fail = status in ("FAILED", "ERROR", "FAIL")
     if is_skip:
         return "⚪", "Skipped"
-    if has_fallback:
-        if is_pass:
-            return "🔴", "Passed+Fallback"
-        return "🔴", "Failed+Fallback"
     if not has_offload_data:
         if is_pass:
             return "⚪", "Passed (no data)"
         return "🟡", "Failed (no data)"
+    if is_fail:
+        if last_record_fallback:
+            return "🔴", "Failed+Fallback"
+        return "🟡", "Failed+Offload"
+    if has_fallback:
+        return "🔴", "Passed+Fallback"
     if is_pass:
         return "🟢", "Passed+Offload"
-    if status in ("FAILED", "ERROR", "FAIL"):
-        return "🟡", "Failed+Offload"
     return "🟡", "Failed"
 
 
@@ -236,8 +241,10 @@ def analyze_json_tests(suites):
             records = t.get("records", [])
             has_fallback = any(r.get("offload") == "FALLBACK" for r in records)
             has_offload_data = len(records) > 0
+            last_record_fallback = (records[-1].get("offload") == "FALLBACK") if records else None
             color, label = classify_test(
-                t.get("status", "PASSED"), has_fallback, has_offload_data)
+                t.get("status", "PASSED"), has_fallback, has_offload_data,
+                last_record_fallback)
             tests.append({
                 "suite": suite_name,
                 "test": t["name"],
@@ -469,8 +476,10 @@ def format_summary(summary, json_tests, suites=None):
                 has_fallback = any(r.get("offload") == "FALLBACK"
                                    for r in records)
                 has_offload_data = len(records) > 0
+                last_fb = (records[-1].get("offload") == "FALLBACK") if records else None
                 _, label = classify_test(
-                    t.get("status", "PASSED"), has_fallback, has_offload_data)
+                    t.get("status", "PASSED"), has_fallback, has_offload_data,
+                    last_fb)
                 counts[label] += 1
             total = sum(counts.values())
             po = counts.get("Passed+Offload", 0)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org


(gluten) 04/07: Simplify analyze-ansi.py: English prompt, remove dead code, add AI disclaimer

Posted by ch...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a commit to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit 8dfa2c00963c6d30b20fe39248c61ce47f6e25d8
Author: Chang chen <ch...@apache.org>
AuthorDate: Tue Apr 21 09:24:09 2026 +0800

    Simplify analyze-ansi.py: English prompt, remove dead code, add AI disclaimer
    
    - Translate ANALYSIS_PROMPT_TEMPLATE from Chinese to English
    - Delete unused analyze-ansi-results.py (unreferenced anywhere)
    - Remove unused _extract_expected_got() function
    - Add accuracy disclaimer to AI analysis footer
    - Update arg help text (Copilot CLI → GitHub Models API)
    - Rename json_tests → json_records in main() for clarity
    
    Co-Authored-By: Claude Opus 4 <no...@anthropic.com>
---
 .github/scripts/analyze-ansi-results.py | 722 --------------------------------
 .github/scripts/analyze-ansi.py         |  97 ++---
 2 files changed, 46 insertions(+), 773 deletions(-)

diff --git a/.github/scripts/analyze-ansi-results.py b/.github/scripts/analyze-ansi-results.py
deleted file mode 100644
index 4a17d96121..0000000000
--- a/.github/scripts/analyze-ansi-results.py
+++ /dev/null
@@ -1,722 +0,0 @@
-#!/usr/bin/env python3
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements.  See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License.  You may obtain a copy of the License at
-#
-#    http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Analyze ANSI mode test results from surefire XML and/or test logs.
-
-Supports two input formats:
-  --format xml  : Parse surefire XML reports (CI artifacts)
-  --format log  : Parse test log files (local verify-ansi-expressions.sh output)
-
-Both formats are merged when available: XML provides authoritative pass/fail/skip,
-logs provide expression-level offload/fallback data from EXPRESSION_OFFLOAD_SUMMARY blocks.
-
-Three-color classification:
-  🟢 Passed + Offload  — test passes natively in Velox ANSI mode
-  🟡 Failed + Offload  — test runs in Velox but fails (needs ANSI fix)
-  🔴 Passed + Fallback — test passes but fell back to Spark (Velox can't handle it)
-
-Options:
-  --ai           Call GitHub Models API for analysis
-  --pr-comment   Post report as PR comment
-  --report-dir   Directory containing surefire XML reports (default: ./test-reports/)
-  --log-dir      Directory containing test log files
-  --log          Single log file to parse
-
-Environment variables:
-  GH_TOKEN       — GitHub token for PR comments and GitHub Models API
-  AI_MODEL       — Model name for GitHub Models API (default: gpt-4o)
-  PR_NUMBER      — PR number to comment on
-  TRIGGERED_BY   — GitHub user who triggered the analysis
-  RUN_ID         — GitHub Actions run ID
-"""
-import argparse
-import glob
-import json
-import os
-import re
-import subprocess
-import sys
-import xml.etree.ElementTree as ET
-from collections import defaultdict, OrderedDict
-from pathlib import Path
-
-AI_ENDPOINT = "https://models.inference.ai.azure.com/chat/completions"
-ANSI_RE = re.compile(r'\x1b\[[0-9;]*m')
-
-# Log parsing patterns (from analyze-ansi-test-log.py)
-SUITE_RE = re.compile(r'^(Gluten\w+Suite):$')
-OFFLOAD_RE = re.compile(r"^'(.+)' offload to gluten$")
-FALLBACK_RE = re.compile(r"^'(.+)' NOT use gluten$")
-PASSED_RE = re.compile(r'^- (.+?)(?:\s+\(\d+.*\))?$')
-FAILED_RE = re.compile(r'^- (.+?) \*\*\* FAILED \*\*\*(?:\s+\(\d+.*\))?$')
-IGNORED_RE = re.compile(r'^- (.+?) !!! IGNORED !!!$')
-VALIDATION_FAILED_RE = re.compile(r'Validation failed')
-GLUTEN_CHECK_RE = re.compile(r'glutenCheck(?:Expression|ExceptionInExpression)')
-
-NO_EXCEPTION_RE = re.compile(
-    r'Expected exception .+ to be thrown, but no exception was thrown')
-MSG_MISMATCH_RE = re.compile(
-    r"Expected error message containing '(.+?)' but got '(.+?)'")
-WRONG_EXCEPTION_RE = re.compile(
-    r'Expected (\S+) but got (\S+):')
-
-# EXPRESSION_OFFLOAD_SUMMARY markers
-OFFLOAD_SUMMARY_BEGIN = 'EXPRESSION_OFFLOAD_SUMMARY_BEGIN'
-OFFLOAD_SUMMARY_END = 'EXPRESSION_OFFLOAD_SUMMARY_END'
-
-
-# ---------------------------------------------------------------------------
-# Surefire XML parsing
-# ---------------------------------------------------------------------------
-
-def parse_surefire_reports(base_dir):
-    """Parse all surefire XML reports and return structured test results."""
-    results = []
-    xml_files = glob.glob(f"{base_dir}/**/TEST-*.xml", recursive=True)
-    if not xml_files:
-        return results
-
-    for xml_path in xml_files:
-        try:
-            tree = ET.parse(xml_path)
-        except ET.ParseError:
-            continue
-        suite = tree.getroot()
-        suite_name = suite.get("name", Path(xml_path).stem)
-        job_name = _infer_job_name(xml_path)
-
-        for tc in suite.findall("testcase"):
-            test_name = tc.get("name", "unknown")
-            classname = tc.get("classname", suite_name)
-            time_s = float(tc.get("time", "0"))
-
-            failure = tc.find("failure")
-            error = tc.find("error")
-            skipped = tc.find("skipped")
-
-            if skipped is not None:
-                status = "SKIPPED"
-                message = skipped.get("message", "")
-            elif failure is not None:
-                status = "FAILED"
-                message = (failure.get("message") or failure.text or "")[:500]
-            elif error is not None:
-                status = "ERROR"
-                message = (error.get("message") or error.text or "")[:500]
-            else:
-                status = "PASSED"
-                message = ""
-
-            results.append({
-                "suite": classname,
-                "test": test_name,
-                "status": status,
-                "message": message,
-                "time": time_s,
-                "job": job_name,
-            })
-    return results
-
-
-def _infer_job_name(xml_path):
-    parts = Path(xml_path).parts
-    for p in parts:
-        if "spark-test-" in p:
-            return p
-    return "unknown"
-
-
-def _short_job_name(job):
-    """Shorten job name for table display."""
-    job = job.replace("spark-test-", "").replace("-report", "")
-    return job or "unknown"
-
-
-# ---------------------------------------------------------------------------
-# Log file parsing
-# ---------------------------------------------------------------------------
-
-def parse_log(path):
-    """Parse test log and return list of test-level results."""
-    lines = []
-    with open(path, 'r', errors='replace') as f:
-        for raw_line in f:
-            lines.append(ANSI_RE.sub('', raw_line).strip())
-
-    tests = []
-    current_suite = None
-    test_entries = []
-
-    for i, line in enumerate(lines):
-        if not line:
-            continue
-        m = SUITE_RE.match(line)
-        if m:
-            current_suite = m.group(1)
-            continue
-        m = OFFLOAD_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), None))
-            continue
-        m = FALLBACK_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), None))
-            continue
-        m = FAILED_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), 'FAILED'))
-            continue
-        m = IGNORED_RE.match(line)
-        if m:
-            test_entries.append((i, current_suite, m.group(1), 'IGNORED'))
-            continue
-        m = PASSED_RE.match(line)
-        if m and not VALIDATION_FAILED_RE.search(line):
-            test_entries.append((i, current_suite, m.group(1), 'PASSED'))
-            continue
-
-    test_map = OrderedDict()
-    for line_idx, suite, name, result in test_entries:
-        key = (suite, name)
-        if key not in test_map:
-            test_map[key] = {
-                'suite': suite or '(unknown)',
-                'test': name,
-                'result': result,
-                'start_line': line_idx,
-            }
-        else:
-            entry = test_map[key]
-            if result is not None:
-                entry['result'] = result
-            entry['start_line'] = min(entry['start_line'], line_idx)
-
-    test_list = list(test_map.values())
-    for i, t in enumerate(test_list):
-        if i + 1 < len(test_list):
-            t['end_line'] = test_list[i + 1]['start_line']
-        else:
-            t['end_line'] = len(lines)
-
-    results = []
-    for t in test_list:
-        if t['result'] == 'IGNORED':
-            has_fallback = False
-            has_velox = False
-            fail_cause = None
-        else:
-            has_fallback = False
-            has_velox = False
-            fail_cause = None
-            for j in range(t['start_line'], t['end_line']):
-                if VALIDATION_FAILED_RE.search(lines[j]):
-                    has_fallback = True
-                if GLUTEN_CHECK_RE.search(lines[j]):
-                    has_velox = True
-                if t['result'] == 'FAILED' and fail_cause is None:
-                    if NO_EXCEPTION_RE.search(lines[j]):
-                        fail_cause = 'NO_EXCEPTION'
-                    elif MSG_MISMATCH_RE.search(lines[j]):
-                        fail_cause = 'MSG_MISMATCH'
-                    elif WRONG_EXCEPTION_RE.search(lines[j]):
-                        fail_cause = 'WRONG_EXCEPTION'
-            if t['result'] == 'FAILED' and fail_cause is None:
-                fail_cause = 'OTHER'
-
-        results.append({
-            'suite': t['suite'],
-            'test': t['test'],
-            'fallback': has_fallback,
-            'velox': has_velox,
-            'result': t['result'] or 'PASSED',
-            'fail_cause': fail_cause,
-        })
-
-    return results
-
-
-# ---------------------------------------------------------------------------
-# EXPRESSION_OFFLOAD_SUMMARY block parsing
-# ---------------------------------------------------------------------------
-
-def parse_offload_summary_from_logs(log_paths):
-    """Parse EXPRESSION_OFFLOAD_SUMMARY blocks from log files.
-
-    Returns dict: {(suite, test_name): [OffloadRecord...]}
-    where each record is {method, expression, meta, offload, status}.
-    """
-    all_records = {}
-
-    for path in log_paths:
-        in_block = False
-        current_suite = None
-        current_test = None
-
-        with open(path, 'r', errors='replace') as f:
-            for raw_line in f:
-                line = ANSI_RE.sub('', raw_line).strip()
-                # Strip log4j prefix if present
-                if '] ' in line:
-                    line = line[line.rindex('] ') + 2:]
-                # Strip SLF4J/logback prefix: "HH:MM:SS.mmm WARN classname: content"
-                m = re.match(
-                    r'\d{2}:\d{2}:\d{2}\.\d+ \w+ [\w.$]+:\s*(.*)', line)
-                if m:
-                    line = m.group(1)
-
-                if OFFLOAD_SUMMARY_BEGIN in line:
-                    in_block = True
-                    continue
-                if OFFLOAD_SUMMARY_END in line:
-                    in_block = False
-                    current_suite = None
-                    current_test = None
-                    continue
-                if not in_block:
-                    continue
-
-                stripped = line.strip()
-                if stripped.endswith(':') and not stripped.startswith(('N|', 'E|')):
-                    if '|' not in stripped:
-                        name = stripped[:-1].strip()
-                        if current_suite is None:
-                            current_suite = name
-                        else:
-                            current_test = name
-                    continue
-
-                if '|' in stripped and stripped[0] in ('N', 'E'):
-                    parts = stripped.split('|')
-                    if len(parts) >= 5:
-                        record = {
-                            'method': 'checkException' if parts[0] == 'E' else 'checkExpression',
-                            'expression': parts[1],
-                            'meta': parts[2],
-                            'offload': parts[3],
-                            'status': parts[4],
-                        }
-                        key = (current_suite, current_test)
-                        all_records.setdefault(key, []).append(record)
-
-    return all_records
-
-
-# ---------------------------------------------------------------------------
-# Classification
-# ---------------------------------------------------------------------------
-
-def classify_test(status, has_fallback, has_offload_data):
-    """Assign three-color classification."""
-    if status == "SKIPPED":
-        return "⚪", "Skipped"
-    if has_fallback:
-        if status == "PASSED":
-            return "🔴", "Passed+Fallback"
-        return "🔴", "Failed+Fallback"
-    if not has_offload_data:
-        if status == "PASSED":
-            return "⚪", "Passed (no data)"
-        return "🟡", "Failed (no data)"
-    if status == "PASSED":
-        return "🟢", "Passed+Offload"
-    if status in ("FAILED", "ERROR"):
-        return "🟡", "Failed+Offload"
-    return "🟡", "Failed"
-
-
-def determine_fallback(test_key, offload_records):
-    """Determine fallback status and whether offload data exists."""
-    records = offload_records.get(test_key, [])
-    if not records:
-        return False, False
-    return any(r['offload'] == 'FALLBACK' for r in records), True
-
-
-def build_summary(results, offload_records=None):
-    """Build summary with three-color classification."""
-    offload_records = offload_records or {}
-    summary = {
-        "total": len(results),
-        "by_color": defaultdict(int),
-        "by_job": defaultdict(lambda: defaultdict(int)),
-        "failures": [],
-    }
-    for t in results:
-        suite = t.get("suite", "")
-        test = t.get("test", "")
-        status = t.get("status", "PASSED")
-
-        has_fallback = t.get("fallback", False)
-        has_offload_data = False
-        if offload_records:
-            test_key = (suite.split('.')[-1], test)
-            fb, has_data = determine_fallback(test_key, offload_records)
-            has_fallback = has_fallback or fb
-            has_offload_data = has_data
-
-        color, label = classify_test(status, has_fallback, has_offload_data)
-        t["color"] = color
-        t["label"] = label
-        t["fallback"] = has_fallback
-        summary["by_color"][label] += 1
-        job = t.get("job", "unknown")
-        summary["by_job"][job][label] += 1
-        if status in ("FAILED", "ERROR"):
-            summary["failures"].append(t)
-    return summary
-
-
-# ---------------------------------------------------------------------------
-# Report generation
-# ---------------------------------------------------------------------------
-
-def format_markdown_report(summary, results, ai_analysis=None):
-    """Generate markdown report."""
-    lines = ["## ANSI Mode Test Analysis Report\n"]
-
-    lines.append("### Overview\n")
-    lines.append(f"Total tests: **{summary['total']}**\n")
-    lines.append("| Classification | Count |")
-    lines.append("|---|---|")
-    for label in ["Passed+Offload", "Failed+Offload", "Passed+Fallback",
-                  "Failed+Fallback", "Failed", "Passed (no data)",
-                  "Failed (no data)", "Skipped"]:
-        count = summary["by_color"].get(label, 0)
-        if count > 0:
-            color = {"Passed+Offload": "🟢", "Failed+Offload": "🟡",
-                     "Passed+Fallback": "🔴", "Failed+Fallback": "🔴",
-                     "Failed": "🟡", "Passed (no data)": "⚪",
-                     "Failed (no data)": "🟡", "Skipped": "⚪"}.get(label, "")
-            lines.append(f"| {color} {label} | {count} |")
-    lines.append("")
-
-    lines.append("### Per-Job Breakdown\n")
-    for job, counts in sorted(summary["by_job"].items()):
-        lines.append(f"**{job}**")
-        for label, count in sorted(counts.items()):
-            lines.append(f"- {label}: {count}")
-        lines.append("")
-
-    if summary["failures"]:
-        lines.append("### Failed Tests (sample, max 50)\n")
-        lines.append("| Suite | Test | Job | Color | Message |")
-        lines.append("|---|---|---|---|---|")
-        for t in summary["failures"][:50]:
-            msg = t.get("message", "")[:200].replace("|", "\\|").replace("\n", " ")
-            job = _short_job_name(t.get("job", ""))
-            lines.append(
-                f"| {t['suite'].split('.')[-1]} | {t['test']} "
-                f"| {job} | {t['color']} {t['label']} | {msg} |")
-        if len(summary["failures"]) > 50:
-            lines.append(f"\n*...and {len(summary['failures']) - 50} more failures*\n")
-        lines.append("")
-
-    if ai_analysis:
-        lines.append("### AI Analysis\n")
-        lines.append(ai_analysis)
-        lines.append("")
-
-    triggered_by = os.environ.get("TRIGGERED_BY", "unknown")
-    run_id = os.environ.get("RUN_ID", "")
-    lines.append(f"\n---\n*Triggered by @{triggered_by} | "
-                 f"[Workflow run](../actions/runs/{run_id})*")
-    return "\n".join(lines)
-
-
-def format_log_table(tests, fallback_only=False, failed_only=False, suite_filter=None):
-    """Print table for log-based analysis (local usage)."""
-    filtered = tests
-    if suite_filter:
-        filtered = [t for t in filtered if suite_filter in t['suite']]
-    if fallback_only:
-        filtered = [t for t in filtered if t['fallback']]
-    if failed_only:
-        filtered = [t for t in filtered if t['result'] == 'FAILED']
-
-    if not filtered:
-        print("No matching tests found.")
-        return
-
-    sw = max(max(len(t['suite']) for t in filtered), len('Suite'))
-    tw = max(max(len(t['test']) for t in filtered), len('Test'))
-
-    def velox_str(t):
-        if t['result'] == 'IGNORED':
-            return 'N/A'
-        return 'yes' if t['velox'] else 'no'
-
-    def fallback_str(t):
-        if t['result'] == 'IGNORED':
-            return 'N/A'
-        return 'found' if t['fallback'] else 'not found'
-
-    def cause_str(t):
-        return t.get('fail_cause') or ''
-
-    has_failures = any(t['result'] == 'FAILED' for t in filtered)
-    if has_failures:
-        cw = max(max((len(cause_str(t)) for t in filtered), default=5), len('Cause'))
-        header = (f"| {'Suite':<{sw}} | {'Test':<{tw}} | Velox | Fallback  "
-                  f"| Result  | {'Cause':<{cw}} |")
-        sep = (f"|{'-' * (sw + 2)}|{'-' * (tw + 2)}|-------|--------"
-               f"---|---------|{'-' * (cw + 2)}|")
-    else:
-        header = f"| {'Suite':<{sw}} | {'Test':<{tw}} | Velox | Fallback  | Result  |"
-        sep = f"|{'-' * (sw + 2)}|{'-' * (tw + 2)}|-------|-----------|---------|"
-    print(header)
-    print(sep)
-    for t in filtered:
-        v = velox_str(t)
-        fb = fallback_str(t)
-        if has_failures:
-            c = cause_str(t)
-            print(f"| {t['suite']:<{sw}} | {t['test']:<{tw}} | {v:<5} | {fb:<9} "
-                  f"| {t['result']:<7} | {c:<{cw}} |")
-        else:
-            print(f"| {t['suite']:<{sw}} | {t['test']:<{tw}} | {v:<5} | {fb:<9} "
-                  f"| {t['result']:<7} |")
-
-    print()
-    total = len(filtered)
-    passed = sum(1 for t in filtered if t['result'] == 'PASSED')
-    failed = sum(1 for t in filtered if t['result'] == 'FAILED')
-    ignored = sum(1 for t in filtered if t['result'] == 'IGNORED')
-    velox_yes = sum(1 for t in filtered if t.get('velox'))
-    velox_no = sum(1 for t in filtered if not t.get('velox') and t['result'] != 'IGNORED')
-    fb_found = sum(1 for t in filtered if t['fallback'])
-    print(f"Total: {total} | Velox: {velox_yes} | No Velox: {velox_no} | "
-          f"Fallback: {fb_found}")
-    print(f"Passed: {passed} | Failed: {failed} | Ignored: {ignored}")
-
-    if failed > 0:
-        causes = {}
-        for t in filtered:
-            c = t.get('fail_cause')
-            if c:
-                causes[c] = causes.get(c, 0) + 1
-        cause_parts = [f"{c}: {n}" for c, n in sorted(causes.items())]
-        print(f"Failure causes: {' | '.join(cause_parts)}")
-
-    print()
-    print("Per-suite summary:")
-    suites = OrderedDict()
-    for t in filtered:
-        s = t['suite']
-        if s not in suites:
-            suites[s] = {'total': 0, 'velox': 0, 'no_velox': 0, 'fb_found': 0,
-                         'passed': 0, 'failed': 0, 'ignored': 0}
-        suites[s]['total'] += 1
-        if t.get('velox'):
-            suites[s]['velox'] += 1
-        elif t['result'] != 'IGNORED':
-            suites[s]['no_velox'] += 1
-        if t['fallback']:
-            suites[s]['fb_found'] += 1
-        suites[s][t['result'].lower()] += 1
-
-    sn_w = max(len(s) for s in suites)
-    print(f"| {'Suite':<{sn_w}} | Total | Velox | No Velox | Fallback "
-          f"| Passed | Failed | Ignored |")
-    print(f"|{'-' * (sn_w + 2)}|-------|-------|----------|----------|"
-          f"--------|--------|---------|")
-    for s, c in suites.items():
-        print(f"| {s:<{sn_w}} | {c['total']:>5} | {c['velox']:>5} | "
-              f"{c['no_velox']:>8} | {c['fb_found']:>8} | {c['passed']:>6} | "
-              f"{c['failed']:>6} | {c['ignored']:>7} |")
-
-
-# ---------------------------------------------------------------------------
-# AI analysis
-# ---------------------------------------------------------------------------
-
-def call_github_models_api(summary, failures_sample):
-    """Call GitHub Models API for AI analysis."""
-    token = os.environ.get("GH_TOKEN")
-    model = os.environ.get("AI_MODEL", "gpt-4o")
-    if not token:
-        return None
-
-    failure_text = "\n".join(
-        f"- {t['suite'].split('.')[-1]}.{t['test']}: {t['color']} {t['label']} — "
-        f"{t.get('message', '')[:200]}"
-        for t in failures_sample[:30]
-    )
-
-    prompt = f"""Analyze these ANSI SQL mode test results from Apache Gluten (Velox backend).
-
-Summary:
-- Total tests: {summary['total']}
-- 🟢 Passed+Offload (native Velox ANSI): {summary['by_color'].get('Passed+Offload', 0)}
-- 🟡 Failed+Offload (Velox ran but failed): {summary['by_color'].get('Failed+Offload', 0)}
-- 🔴 Passed+Fallback (fell back to Spark): {summary['by_color'].get('Passed+Fallback', 0)}
-
-Sample failures:
-{failure_text}
-
-Provide a brief analysis (under 500 words):
-1. Key failure patterns and root causes
-2. Which expression types need ANSI implementation work
-3. Priority recommendations for fixing"""
-
-    try:
-        import requests
-        resp = requests.post(
-            AI_ENDPOINT,
-            headers={
-                "Authorization": f"Bearer {token}",
-                "Content-Type": "application/json",
-            },
-            json={
-                "model": model,
-                "messages": [{"role": "user", "content": prompt}],
-                "max_tokens": 1000,
-            },
-            timeout=60,
-        )
-        if resp.status_code == 200:
-            return resp.json()["choices"][0]["message"]["content"]
-        else:
-            return (f"*AI analysis unavailable (HTTP {resp.status_code}). "
-                    f"The commenter may not have GitHub Models API access.*")
-    except Exception as e:
-        return f"*AI analysis unavailable: {e}*"
-
-
-# ---------------------------------------------------------------------------
-# Output helpers
-# ---------------------------------------------------------------------------
-
-def post_pr_comment(markdown):
-    pr_number = os.environ.get("PR_NUMBER")
-    if not pr_number:
-        print("PR_NUMBER not set, skipping PR comment")
-        return
-    try:
-        subprocess.run(
-            ["gh", "pr", "comment", pr_number, "--body", markdown],
-            check=True, timeout=30,
-        )
-        print(f"Posted comment to PR #{pr_number}")
-    except (subprocess.CalledProcessError, subprocess.TimeoutExpired,
-            FileNotFoundError) as e:
-        print(f"Failed to post PR comment: {e}")
-
-
-def write_job_summary(markdown):
-    summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
-    if summary_path:
-        with open(summary_path, "a") as f:
-            f.write(markdown)
-        print("Wrote Job Summary")
-
-
-# ---------------------------------------------------------------------------
-# Main
-# ---------------------------------------------------------------------------
-
-def main():
-    parser = argparse.ArgumentParser(
-        description='Analyze Gluten ANSI mode test results')
-    parser.add_argument('--format', choices=['xml', 'log'], default='xml',
-                        help='Input format: xml (surefire reports) or log (test logs)')
-    parser.add_argument('--report-dir', default='./test-reports/',
-                        help='Directory with surefire XML reports')
-    parser.add_argument('--log-dir', default=None,
-                        help='Directory with test log files')
-    parser.add_argument('--log', default=None,
-                        help='Single log file to parse')
-    parser.add_argument('--ai', action='store_true',
-                        help='Call GitHub Models API for analysis')
-    parser.add_argument('--pr-comment', action='store_true',
-                        help='Post report as PR comment')
-    parser.add_argument('--fallback-only', action='store_true',
-                        help='Show only tests that fell back to Spark (log mode)')
-    parser.add_argument('--failed-only', action='store_true',
-                        help='Show only failed tests (log mode)')
-    parser.add_argument('--suite', type=str, default=None,
-                        help='Filter by suite name (log mode)')
-    args = parser.parse_args()
-
-    offload_records = {}
-
-    if args.format == 'log':
-        # Log-based analysis (local mode)
-        log_path = args.log
-        if not log_path:
-            print("--log is required for --format log")
-            sys.exit(1)
-        tests = parse_log(log_path)
-        if not tests:
-            print(f"No tests found in {log_path}")
-            sys.exit(1)
-
-        offload_records = parse_offload_summary_from_logs([log_path])
-
-        for t in tests:
-            key = (t['suite'], t['test'])
-            records = offload_records.get(key, [])
-            if records:
-                t['fallback'] = any(r['offload'] == 'FALLBACK' for r in records)
-                t['velox'] = any(r['offload'] == 'OFFLOAD' for r in records)
-
-        format_log_table(tests, fallback_only=args.fallback_only,
-                         failed_only=args.failed_only, suite_filter=args.suite)
-        return
-
-    # XML-based analysis (CI mode)
-    results = parse_surefire_reports(args.report_dir)
-
-    # Parse offload summary from log files if available
-    log_paths = []
-    if args.log_dir:
-        log_paths = glob.glob(f"{args.log_dir}/**/*.log", recursive=True)
-        log_paths += glob.glob(f"{args.log_dir}/**/*.txt", recursive=True)
-    if args.log:
-        log_paths.append(args.log)
-    if log_paths:
-        offload_records = parse_offload_summary_from_logs(log_paths)
-
-    if not results:
-        msg = ("## ANSI Mode Test Analysis\n\nNo test reports found. "
-               "Build may have failed — check individual job logs.")
-        if args.pr_comment:
-            post_pr_comment(msg)
-        write_job_summary(msg)
-        print("No surefire reports found")
-        sys.exit(0)
-
-    summary = build_summary(results, offload_records)
-
-    ai_analysis = None
-    if args.ai:
-        ai_analysis = call_github_models_api(summary, summary["failures"])
-
-    report = format_markdown_report(summary, results, ai_analysis)
-
-    if args.pr_comment:
-        post_pr_comment(report)
-    else:
-        print(report)
-    write_job_summary(report)
-
-    print(f"Analysis complete: {summary['total']} tests, "
-          f"{len(summary['failures'])} failures")
-    if offload_records:
-        print(f"Offload records parsed from {len(log_paths)} log file(s), "
-              f"{len(offload_records)} test entries")
-
-
-if __name__ == "__main__":
-    main()
diff --git a/.github/scripts/analyze-ansi.py b/.github/scripts/analyze-ansi.py
index 649a734f0a..98c3d91633 100644
--- a/.github/scripts/analyze-ansi.py
+++ b/.github/scripts/analyze-ansi.py
@@ -44,48 +44,50 @@ WRONG_EXCEPTION_RE = re.compile(r"Expected (\S+) but got (\S+):")
 MSG_MISMATCH_RE = re.compile(r"Expected error message containing")
 
 ANALYSIS_PROMPT_TEMPLATE = """\
-你是 Gluten 项目的 ANSI 模式测试分析专家。Gluten 是 Apache Spark 的 native engine 加速插件,
-通过 Velox (C++) 后端 offload 表达式计算。ANSI 模式要求对溢出、类型转换错误等抛出异常。
+You are an ANSI mode test analysis expert for the Gluten project. Gluten is a native engine \
+acceleration plugin for Apache Spark that offloads expression evaluation to Velox (C++). \
+ANSI mode requires throwing exceptions on overflow, invalid type casts, etc.
 
-以下是 JSON 表达式测试(非 XML suite 测试)的结构化输出:
+Below is the structured output from JSON expression tests (not XML suite tests):
 
 ```json
 {json_data}
 ```
 
-请只分析 JSON 表达式测试数据,不要包含 XML suite 测试统计。直接输出关键发现,不需要总体概览。
-
-请按以下结构生成分析报告(Markdown 格式,中文):
-
-## 关键发现
-- 失败集中区域表(Suite / 失败数 / 主要症结)
-- failCause 类型统计表(类型 / 数量 / 占比 / 解读):
-  - WRONG_EXCEPTION: Velox 抛了异常但被 Spark 调度层包装为 SparkException,丢失原始异常类型
-  - NO_EXCEPTION: Velox 在 ANSI 模式下未抛出期望的异常
-  - OTHER: 计算结果不匹配或其他错误
-- 对 WRONG_EXCEPTION 做根因深度分析(异常包装链路径、关键代码位置)
-- 对 NO_EXCEPTION 按根因细分(算术/cast/datetime 等)
-
-## 修复建议(只列 P0 / P1 / P2 三个优先级)
-每个修复建议包含:
-- 症状:测试失败的模式描述
-- 根因:具体代码路径和逻辑问题
-- 修复点:文件路径 + 改动方向
-- 代表测试:受影响的典型测试名
-- 预计影响:修复后可转绿的测试数
-
-关键源码位置(供参考):
-- 异常查找: gluten-ut/common/src/test/scala/org/apache/spark/sql/GlutenTestsTrait.scala (findCause 方法)
-- 异常包装: gluten-arrow/src/main/java/org/apache/gluten/vectorized/ColumnarBatchOutIterator.java (translateException)
-- 表达式转换: gluten-core/.../ExpressionConverter.scala
-- 类型映射: gluten-substrait/.../ConverterUtils.scala (getTypeNode)
+Analyze only the JSON expression test data. Output key findings directly — no overview section.
+
+Generate analysis in Markdown:
+
+## Key Findings
+- Failure hotspot table (Suite / Failures / Root Cause)
+- failCause type statistics table (Type / Count / % / Interpretation):
+  - WRONG_EXCEPTION: Velox threw an exception but Spark's scheduling layer wrapped it as \
+SparkException, losing the original exception type
+  - NO_EXCEPTION: Velox did not throw the expected exception in ANSI mode
+  - OTHER: Result mismatch or other errors
+- Root cause deep analysis for WRONG_EXCEPTION (exception wrapping chain path, key code locations)
+- Breakdown of NO_EXCEPTION by root cause (arithmetic/cast/datetime etc.)
+
+## Fix Recommendations (P0 / P1 / P2 only)
+Each recommendation includes:
+- Symptom: test failure pattern
+- Root Cause: specific code path and logic issue
+- Fix Point: file path + change direction
+- Representative Tests: affected test names
+- Estimated Impact: number of tests that would turn green after fix
+
+Key source locations (for reference):
+- Exception lookup: gluten-ut/common/src/test/scala/org/apache/spark/sql/GlutenTestsTrait.scala (findCause method)
+- Exception wrapping: gluten-arrow/src/main/java/org/apache/gluten/vectorized/ColumnarBatchOutIterator.java (translateException)
+- Expression conversion: gluten-core/.../ExpressionConverter.scala
+- Type mapping: gluten-substrait/.../ConverterUtils.scala (getTypeNode)
 - Velox Cast: ep/build-velox/build/velox_ep/velox/functions/sparksql/SparkCastExpr.cpp
-- Velox 算术: ep/build-velox/build/velox_ep/velox/functions/sparksql/Arithmetic.cpp
+- Velox Arithmetic: ep/build-velox/build/velox_ep/velox/functions/sparksql/Arithmetic.cpp
 
-限制:
-- 使用 Markdown 表格,不要用 ASCII box drawing 字符
-- 修复建议最多 3 个
-- 如果可以访问源码,请读取关键文件验证根因分析
+Constraints:
+- Use Markdown tables, no ASCII box drawing characters
+- Maximum 3 fix recommendations
+- If source code is accessible, read key files to verify root cause analysis
 """
 
 
@@ -120,12 +122,6 @@ def _extract_short_message(message):
     return message.split("\n")[0][:120]
 
 
-def _extract_expected_got(message):
-    m = WRONG_EXCEPTION_RE.search(message)
-    if m:
-        return m.group(1), m.group(2)
-    return None, None
-
 
 # ===========================================================================
 # DATA LAYER
@@ -729,7 +725,9 @@ def format_full(summary, json_records, categories, suites=None,
         parts.append("<details>")
         parts.append("<summary>🤖 AI Deep Analysis</summary>\n")
         parts.append(ai_content)
-        parts.append(f"\n---\n*Generated by {ai_model}*")
+        parts.append(f"\n---\n*Generated by {ai_model}. "
+                     f"AI analysis may not be fully accurate — "
+                     f"please verify before acting on recommendations.*")
         parts.append("</details>")
     return "\n".join(parts)
 
@@ -889,24 +887,21 @@ def main():
     parser.add_argument("--job-summary", action="store_true")
     parser.add_argument("--output-file", help="Write output to file")
     parser.add_argument("--ai-analysis", action="store_true",
-                        help="Call Copilot CLI for AI deep analysis")
+                        help="Call GitHub Models API for AI deep analysis")
     parser.add_argument("--ai-model", default="",
-                        help="AI model for Copilot CLI (default: claude-sonnet-4)")
+                        help="AI model (default: gpt-4.1)")
     args = parser.parse_args()
 
-    # Load data
     suites = load_json_data(args.json_dir)
     xml_results = load_surefire_xml(args.report_dir)
 
-    # Analyze
-    json_tests = analyze_json_tests(suites)
+    json_records = analyze_json_tests(suites)
     xml_tests = analyze_xml_tests(xml_results)
-    summary = build_summary(json_tests, xml_tests)
+    summary = build_summary(json_records, xml_tests)
     categories = analyze_expression_matrix(suites)
 
-    # Format output
     if args.mode == "summary":
-        report = format_summary(summary, json_tests, suites)
+        report = format_summary(summary, json_records, suites)
     elif args.mode == "matrix":
         report = format_matrix(categories)
     elif args.mode == "full":
@@ -916,10 +911,10 @@ def main():
             model = args.ai_model or os.environ.get("AI_MODEL", "")
             ai_content, ai_model = call_ai_analysis(
                 ai_context, model or None)
-        report = format_full(summary, json_tests, categories, suites,
+        report = format_full(summary, json_records, categories, suites,
                              ai_content=ai_content, ai_model=ai_model)
     elif args.mode == "json":
-        report = format_json_output(summary, json_tests, xml_tests, categories)
+        report = format_json_output(summary, json_records, xml_tests, categories)
 
     # Output
     if args.output_file:


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org


(gluten) 01/07: [GLUTEN-10134][VL] Per-Suite Summary: use 4-label columns with Passed+Offload ratio

Posted by ch...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a commit to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit c98b7018cb0071952787a90dd12cb6fa1573a59c
Author: Chang chen <ch...@apache.org>
AuthorDate: Tue Apr 21 08:28:00 2026 +0800

    [GLUTEN-10134][VL] Per-Suite Summary: use 4-label columns with Passed+Offload ratio
    
    Replace Total/Pass/Fail/Offload/Fallback columns with the 4 classification
    labels (Passed+Offload, Failed+Offload, Passed+Fallback, Failed+Fallback).
    Remove Category column, sort by category. Show Passed+Offload percentage.
    
    Co-Authored-By: Claude Opus 4 <no...@anthropic.com>
---
 .github/scripts/analyze-ansi.py | 39 +++++++++++++++++++++------------------
 1 file changed, 21 insertions(+), 18 deletions(-)

diff --git a/.github/scripts/analyze-ansi.py b/.github/scripts/analyze-ansi.py
index da57e8e768..d8d032d014 100644
--- a/.github/scripts/analyze-ansi.py
+++ b/.github/scripts/analyze-ansi.py
@@ -455,29 +455,32 @@ def format_summary(summary, json_tests, suites=None):
     # --- Per-Suite Summary (JSON only) ---
     if suites:
         lines.append("### Per-Suite Summary\n")
-        lines.append("| Suite | Category | Total | Pass | Fail "
-                     "| Offload | Fallback |")
-        lines.append("|---|---|---|---|---|---|---|")
+        lines.append("| Suite | 🟢 Passed+Offload | 🟡 Failed+Offload "
+                     "| 🔴 Passed+Fallback | 🔴 Failed+Fallback |")
+        lines.append("|---|---|---|---|---|")
+        suite_rows = []
         for s in suites:
             name = s.get("suite", "").split(".")[-1]
             cat = s.get("category", "")
             tests = s.get("tests", [])
-            total = len(tests)
-            passed = failed = off = fb = 0
+            counts = defaultdict(int)
             for t in tests:
-                st = t.get("status")
-                if st == "PASS":
-                    passed += 1
-                elif st == "FAIL":
-                    failed += 1
-                for r in t.get("records", []):
-                    ol = r.get("offload")
-                    if ol == "OFFLOAD":
-                        off += 1
-                    elif ol == "FALLBACK":
-                        fb += 1
-            lines.append(f"| {name} | {cat} | {total} | {passed} "
-                         f"| {failed} | {off} | {fb} |")
+                records = t.get("records", [])
+                has_fallback = any(r.get("offload") == "FALLBACK"
+                                   for r in records)
+                has_offload_data = len(records) > 0
+                _, label = classify_test(
+                    t.get("status", "PASSED"), has_fallback, has_offload_data)
+                counts[label] += 1
+            total = sum(counts.values())
+            po = counts.get("Passed+Offload", 0)
+            pct = f"{po * 100 / total:.0f}%" if total else "0%"
+            suite_rows.append((cat, name, po, pct,
+                               counts.get("Failed+Offload", 0),
+                               counts.get("Passed+Fallback", 0),
+                               counts.get("Failed+Fallback", 0)))
+        for cat, name, po, pct, fo, pfb, ffb in sorted(suite_rows):
+            lines.append(f"| {name} | {po} ({pct}) | {fo} | {pfb} | {ffb} |")
         lines.append("")
 
     # --- Failure Cause Analysis (JSON only) ---


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org


(gluten) 06/07: Fix analyze-only: increase run search window from 15 to 50

Posted by ch...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

baibaichen pushed a commit to branch feature/ansi-baseline-workflow
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit 2c62c21a81686ae360171cd8789ebc17e76b0bba
Author: Chang chen <ch...@apache.org>
AuthorDate: Tue Apr 21 09:31:40 2026 +0800

    Fix analyze-only: increase run search window from 15 to 50
    
    The artifact-bearing run was pushed out of the 15-run search window
    by subsequent analyze-only runs, causing "no artifacts found" failures.
    
    Co-Authored-By: Claude Opus 4 <no...@anthropic.com>
---
 .github/workflows/velox_backend_ansi.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/velox_backend_ansi.yml b/.github/workflows/velox_backend_ansi.yml
index 0a40a3aad3..0cddf230f1 100644
--- a/.github/workflows/velox_backend_ansi.yml
+++ b/.github/workflows/velox_backend_ansi.yml
@@ -539,7 +539,7 @@ jobs:
           WORKFLOW="velox_backend_ansi.yml"
           PR_BRANCH="${{ needs.check-comment.outputs.pr_ref }}"
           echo "Looking for latest ANSI run with artifacts on branch=${PR_BRANCH}..."
-          CANDIDATE_IDS=$(gh api "repos/${REPO}/actions/workflows/${WORKFLOW}/runs?branch=${PR_BRANCH}&per_page=15" \
+          CANDIDATE_IDS=$(gh api "repos/${REPO}/actions/workflows/${WORKFLOW}/runs?branch=${PR_BRANCH}&per_page=50" \
             --jq '.workflow_runs[] | select(.id != ${{ github.run_id }}) | .id')
           RUN_ID=""
           for cid in $CANDIDATE_IDS; do


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@gluten.apache.org
For additional commands, e-mail: commits-help@gluten.apache.org