Skip to content

Studio: JSON and Markdown validator blocks - #10710

Merged
danielhanchen merged 10 commits into
unslothai:mainfrom
Souravrajvi0:feat/data-recipes-followup-9d69
Oct 2, 2026
Merged

danielhanchen merged 10 commits into
unslothai:mainfrom
Souravrajvi0:feat/data-recipes-followup-9d69

Conversation

@Souravrajvi0

@Souravrajvi0 Souravrajvi0 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #10637 / #10708.

Adds JSON check and Markdown check validator blocks under Checks in Recipe Studio.

  • Target any generated field (AI text/structured, formula, sampler)
  • Backend registers local validators via unsloth_json_validator and unsloth_markdown_validator
  • Graph connection plumbing and unit tests included

Split for review (same original umbrella work, separate PRs):

Pairs with #10708 (download button) - no overlap.

Before / after

The Recipe Studio "Checks" block group gains JSON check and Markdown check (left: main, right: this PR).

Checks block group before and after

chatgpt-codex-connector[bot]

This comment was marked as outdated.

Add JSON check and Markdown check validator blocks under Checks in Recipe
Studio. Targets any generated field (AI text/structured, formula, sampler).
Backend registers local validators via unsloth_json_validator and
unsloth_markdown_validator markers with hardened parsing.
@Souravrajvi0 Souravrajvi0 reopened this Sep 10, 2026
@Souravrajvi0
Souravrajvi0 force-pushed the feat/data-recipes-followup-9d69 branch from 2eb99cd to c7dcaba Compare September 10, 2026 14:30
@Souravrajvi0 Souravrajvi0 changed the title Studio: model blocks, JSON/markdown checks, live dataset preview Studio: JSON and Markdown validator blocks Sep 10, 2026
@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

@danielhanchen — done, split per your feedback.

This PR (#10710) now contains only the JSON & Markdown validator blocks (text_format_validators.py + frontend wiring). The branch was narrowed to validators-only.

The other two pieces are in separate PRs:

Each can be reviewed and merged independently. Happy to tackle any follow-ups on whichever PR you want to look at first.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 1, 2026
@unslothai unslothai deleted a comment from Souravrajvi0 Oct 1, 2026
@unslothai unslothai deleted a comment from Souravrajvi0 Oct 1, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 1, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #10710, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#293.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 2d9babbe1 (this PR's c026302f9)

chatgpt-codex-connector[bot] on studio/frontend/src/features/recipe-studio/utils/graph/recipe-graph-connection.ts (on the mirror)

@@ -439,6 +453,17 @@ export function applyRecipeConnection(
     };
     return { edges: nextEdges, configs: { ...configs, [target.id]: next } };
   }
+  if (target.kind === "validator" && isTextFormatValidator(target)) {
+    if (!isTextFormatValidatorTarget(source)) {
+      return { edges: nextEdges };

P2 Badge Reject unsupported sources before adding validator edges

When a seed or another validator is dragged into a JSON/Markdown validator through the data handles, isValidRecipeConnection accepts it as an ordinary data-lane connection. This branch then returns nextEdges, preserving the new visual edge while leaving target_columns unchanged, so the check still fails recipe validation and the misleading edge survives saving. Reject these sources before addEdge, or return the original edges here.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from shimmyshimmer:

Not changing: same as the existing Python/SQL/JS checks, which also keep a plain data edge from an unrelated source; the check's own target is unchanged and recipe validation still names the missing target. Cosmetic, not a correctness bug.

chatgpt-codex-connector[bot] on studio/backend/core/data_recipe/text_format_validators.py (on the mirror)

@@ -0,0 +1,255 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import json
+import re
+from copy import deepcopy
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any
+
+JSON_VALIDATION_FN_MARKER = "unsloth_json_validator"
+MARKDOWN_VALIDATION_FN_MARKER = "unsloth_markdown_validator"
+
+# CommonMark fenced code blocks: https://spec.commonmark.org/0.31.2/#fenced-code-blocks
+_MARKDOWN_FENCE_OPEN_RE = re.compile(r"^ {0,3}(`{3,}(?=[^`]*$)|~{3,})")
+_MARKDOWN_FENCE_CLOSE_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})[ \t]*$")
+
+
+@dataclass(frozen = True)
+class TextFormatLocalCallableValidatorSpec:
+    name: str
+    drop: bool
+    target_columns: list[str]
+    batch_size: int
+    format_kind: str
+
+
+def split_text_format_local_callable_validators(
+    recipe_core: dict[str, Any],
+) -> tuple[dict[str, Any], list[TextFormatLocalCallableValidatorSpec]]:
+    columns = recipe_core.get("columns")
+    if not isinstance(columns, list):
+        return recipe_core, []
+
+    sanitized = deepcopy(recipe_core)
+    sanitized_columns = sanitized.get("columns")
+    if not isinstance(sanitized_columns, list):
+        return sanitized, []
+
+    kept_columns: list[Any] = []
+    specs: list[TextFormatLocalCallableValidatorSpec] = []
+
+    for column in sanitized_columns:
+        if not isinstance(column, dict):
+            kept_columns.append(column)
+            continue
+
+        maybe_spec = _parse_text_format_spec(column = column)
+        if maybe_spec is None:
+            kept_columns.append(column)
+            continue
+        specs.append(maybe_spec)
+
+    sanitized["columns"] = kept_columns
+    return sanitized, specs
+
+
+def register_text_format_local_callable_validators(
+    *, builder, specs: list[TextFormatLocalCallableValidatorSpec]
+) -> None:
+    if not specs:
+        return
+
+    from data_designer.config.column_configs import ValidationColumnConfig
+    from data_designer.config.validator_params import (
+        LocalCallableValidatorParams,
+        ValidatorType,
+    )
+
+    for spec in specs:
+        validation_function = _build_text_format_validation_function(spec.format_kind)
+        builder.add_column(
+            ValidationColumnConfig(
+                name = spec.name,
+                drop = spec.drop,
+                target_columns = spec.target_columns,
+                validator_type = ValidatorType.LOCAL_CALLABLE,
+                validator_params = LocalCallableValidatorParams(
+                    validation_function = validation_function,
+                ),
+                batch_size = spec.batch_size,
+            )
+        )
+
+
+def _parse_text_format_spec(
+    *, column: dict[str, Any]
+) -> TextFormatLocalCallableValidatorSpec | None:
+    if str(column.get("column_type") or "").strip() != "validation":
+        return None
+    if str(column.get("validator_type") or "").strip() != "local_callable":
+        return None
+
+    params = column.get("validator_params")
+    if not isinstance(params, dict):
+        return None
+
+    fn_raw = params.get("validation_function")
+    fn_name = fn_raw.strip() if isinstance(fn_raw, str) else ""
+    format_kind = _text_format_kind_from_marker(fn_name)
+    if format_kind is None:
+        return None
+
+    name = str(column.get("name") or "").strip()
+    if not name:
+        return None
+
+    target_columns_raw = column.get("target_columns")
+    target_columns = (
+        [value.strip() for value in target_columns_raw if isinstance(value, str) and value.strip()]
+        if isinstance(target_columns_raw, list)
+        else []
+    )
+    if not target_columns:
+        return None
+
+    return TextFormatLocalCallableValidatorSpec(
+        name = name,
+        drop = bool(column.get("drop") is True),
+        target_columns = target_columns,
+        batch_size = _parse_batch_size(column.get("batch_size")),
+        format_kind = format_kind,
+    )
+
+
+def _text_format_kind_from_marker(fn_name: str) -> str | None:
+    if fn_name == JSON_VALIDATION_FN_MARKER:
+        return "json"
+    if fn_name == MARKDOWN_VALIDATION_FN_MARKER:
+        return "markdown"
+    return None
+
+
+def _parse_batch_size(value: Any) -> int:
+    try:
+        parsed = int(value)
+    except (TypeError, ValueError):
+        return 10
+    return parsed if parsed >= 1 else 10
+
+
+@lru_cache(maxsize = 4)
+def _build_text_format_validation_function(format_kind: str):
+    def _validator(df):
+        import pandas as pd
+
+        row_count = int(len(df.index))
+        if row_count == 0:
+            return pd.DataFrame({"is_valid": []})
+
+        value_column = str(df.columns[0]) if len(df.columns) > 0 else ""
+        values = (
+            ["" for _ in range(row_count)]
+            if not value_column
+            else [_coerce_validation_value(value) for value in df[value_column].tolist()]
+        )
+
+        results = [_validate_text_format(value = value, format_kind = format_kind) for value in values]
+        return pd.DataFrame(results)
+
+    _validator.__name__ = f"{format_kind}_format_validator"
+    return _validator
+
+
+def _coerce_validation_value(value: Any) -> Any:
+    import pandas as pd
+
+    if isinstance(value, (dict, list)):
+        return value
+    if value is None or pd.isna(value):
+        return ""
+    if isinstance(value, (bool, int, float)):
+        return value
+    return str(value)
+
+
+def _reject_json_constant(constant: str) -> float:
+    raise ValueError(f"Invalid JSON constant: {constant}")
+
+
+def _validate_text_format(*, value: Any, format_kind: str) -> dict[str, Any]:
+    if format_kind == "json":
+        return _validate_json_text(value)
+    return _validate_markdown_text(value)
+
+
+def _validate_json_text(value: Any) -> dict[str, Any]:
+    if isinstance(value, (dict, list, bool, int, float)):
+        payload = value
+    else:
+        stripped = str(value).strip()
+        if not stripped:
+            return _invalid_result("JSON value is empty.")
+        try:
+            payload = json.loads(stripped, parse_constant = _reject_json_constant)
+        except (json.JSONDecodeError, ValueError, RecursionError) as exc:
+            return _invalid_result(str(exc))
+    try:
+        json.dumps(payload, allow_nan = False)
+    except (TypeError, ValueError) as exc:
+        return _invalid_result(str(exc))
+    return _valid_result()
+
+
+# Markdown accepts unmatched brackets and parentheses as text ("1) item", "Status (draft"),
+# so an unclosed code fence is the only structural break worth rejecting.
+def _has_unclosed_markdown_fence(text: str) -> bool:
+    fence = ""
+    for line in text.splitlines():
+        if not fence:
+            match = _MARKDOWN_FENCE_OPEN_RE.match(line)
+            if match:
+                fence = match.group(1)

P2 Badge Track fenced blocks inside Markdown containers

When generated Markdown opens a fence inside a block quote or list, such as > ```python\n> print(1), CommonMark recognizes a fenced code block, but this regex sees the > or list marker instead of the fence and leaves fence empty. The Markdown check therefore accepts these unterminated nested fences even though rejecting unclosed fences is its only structural validation; account for container prefixes or use parser state when detecting fences.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: unterminated fences nested in block quotes or lists are a rare shape for generated text, and missing them only lets a row through (no false rejections). A full container-aware CommonMark parser is out of scope for this check.

Verdict

The round did not reach a clean review on the mirror before it closed.

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 1, 2026
@danielhanchen
danielhanchen merged commit 9834db0 into unslothai:main Oct 2, 2026
6 of 52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants