Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Add None/empty content detection for conversation datasets (#4438)

Leo Borcherdingf4873182e068
diff --git a/studio/backend/utils/datasets/dataset_none_detect.py b/studio/backend/utils/datasets/dataset_none_detect.py
new file mode 100644
index 00000000000..1e884271cca
--- /dev/null
+++ b/studio/backend/utils/datasets/dataset_none_detect.py
@@ -0,0 +1,888 @@
+"""
+dataset_none_detect.py
+
+Detect None/empty content turns in conversation datasets.
+Reports findings without modifying data.
+
+Usage:
+ from .dataset_none_detect import scan_dataset, print_report
+ stats = scan_dataset(dataset) # auto-detect + scan
+ stats = scan_dataset(dataset, fmt="chatml") # explicit format
+ print_report(stats, stats["format"])
+
+Dependencies: only `datasets` (already in studio/unsloth) + stdlib.
+
+Supported formats (via FORMAT_REGISTRY):
+ alpaca instruction/output instruction + output must be set
+ chatml messages/conversations/texts role + content per turn
+ sharegpt conversations from/value per turn
+ gptoss messages (alias: gpt-oss) role/content; has a developer turn
+
+Any role/content chat template matches the chatml entry, so new templates need
+no change; add a FORMAT_REGISTRY entry only for a genuinely new column/turn shape.
+"""
+
+from datasets import Dataset
+
+# ---------------------------------------------------------------------------
+# Conversation column probing (shared by detection + scanning)
+# ---------------------------------------------------------------------------
+
+# Candidate column names for conversational datasets, checked in priority order.
+CONVERSATION_COLUMNS = ("messages", "conversations", "texts")
+
+# Minimum turn key sets that identify a column as conversational (not e.g. messages=[{"id":1}]).
+_CHAT_KEY_SETS = (frozenset({"role", "content"}), frozenset({"from", "value"}))
+
+
+def _probe_conversation(dataset: Dataset, candidates = None):
+ """
+ Probe a dataset for its conversation column and turn structure.
+
+ candidates - iterable of column names to try, in priority order.
+ Defaults to CONVERSATION_COLUMNS when None.
+
+ Returns a dict with:
+ column - name of the conversation column found
+ turn_keys - set of keys present in the first turn dict
+ roles - set of all role values seen across the first few samples
+
+ Returns None if no conversation column is found.
+ """
+ if candidates is None:
+ candidates = CONVERSATION_COLUMNS
+ columns = set(dataset.column_names)
+ # Remember the first all-corrupt candidate, but keep probing: a later column
+ # may be healthy and should win (e.g. bad messages, good conversations).
+ all_corrupt_fallback = None
+ for col in candidates:
+ if col not in columns:
+ continue
+ # Scan up to 100 rows - row 0 alone may be empty or malformed.
+ first = None
+ for i in range(min(len(dataset), 100)):
+ sample = dataset[i][col]
+ if not isinstance(sample, list) or len(sample) == 0:
+ continue
+ # Skip non-dict leading turns (e.g. [None, {"role": ...}]).
+ first_turn = next((t for t in sample if isinstance(t, dict)), None)
+ if first_turn is not None:
+ first = first_turn
+ break
+ if first is None:
+ # No usable dict turn in 100 rows. Record an all_corrupt fallback,
+ # marking it plausible only if we saw turn-shaped data (a None cell or
+ # a list holding a dict/None turn); scalars and list-of-strings must
+ # not look like chatml. Upgrade a non-plausible fallback when a later
+ # candidate is plausible, so probe order keeps the best match.
+ if all_corrupt_fallback is None or not all_corrupt_fallback.get(
+ "has_plausible_turns"
+ ):
+ has_plausible_turns = False
+ for i in range(min(len(dataset), 100)):
+ cell = dataset[i][col]
+ if cell is None:
+ has_plausible_turns = True
+ break
+ # A struct-typed cell (single dict, not a list) is metadata,
+ # not chat: leave it for "unknown format", matching
+ # format_detection.py.
+ if isinstance(cell, list):
+ # Plausible only if the list holds a dict/None turn; empty
+ # lists and list-of-strings are not chat data.
+ if any(t is None or isinstance(t, dict) for t in cell):
+ has_plausible_turns = True
+ break
+ all_corrupt_fallback = {
+ "column": col,
+ "turn_keys": set(),
+ "roles": set(),
+ "all_corrupt": True,
+ "has_plausible_turns": has_plausible_turns,
+ }
+ continue
+
+ # Use the same 100-row window to gather keys/roles.
+ turn_keys = set()
+ roles = set()
+ for i in range(min(len(dataset), 100)):
+ conv = dataset[i][col]
+ if isinstance(conv, list):
+ for t in conv:
+ if isinstance(t, dict):
+ turn_keys.update(t.keys())
+ r = t.get("role") or t.get("from")
+ if r:
+ roles.add(str(r))
+ # Column lacks a full chat key pair. If it still has a conversational key
+ # (role/from/content/value) it is a corrupt-but-real chat column, so save
+ # a plausible fallback for find_none_chatml to flag. Pure metadata (e.g.
+ # [{"id":1}]) is not plausible, so a later real-but-corrupt column (e.g.
+ # conversations=None) can still win.
+ _CONV_KEYS = {"role", "from", "content", "value"}
+ if not any(keys <= turn_keys for keys in _CHAT_KEY_SETS):
+ schema_less_plausible = bool(turn_keys & _CONV_KEYS)
+ if all_corrupt_fallback is None or not all_corrupt_fallback.get(
+ "has_plausible_turns"
+ ):
+ all_corrupt_fallback = {
+ "column": col,
+ "turn_keys": turn_keys,
+ "roles": roles,
+ "all_corrupt": True,
+ "has_plausible_turns": schema_less_plausible,
+ }
+ continue
+ return {"column": col, "turn_keys": turn_keys, "roles": roles}
+ # No healthy column found; return the all_corrupt fallback if any.
+ return all_corrupt_fallback
+
+
+# None-detection helpers
+# ---------------------------------------------------------------------------
+
+
+def is_none_or_empty(value) -> bool:
+ """True if value is None, empty string, whitespace-only, or an empty/whitespace-only VLM content block list."""
+ if value is None:
+ return True
+ if isinstance(value, str):
+ # Treat zero-width/BOM chars (U+FEFF/200B/200C/200D/2060) as empty too;
+ # they render invisibly. Two-pass strip (ws, invisibles, ws) catches
+ # mixed cases like "\u200b \u200b".
+ stripped = value.strip().strip("\ufeff\u200b\u200c\u200d\u2060").strip()
+ if not stripped:
+ return True
+ if isinstance(value, list):
+ # VLM content blocks, e.g. [{"type":"text",...}, {"type":"image",...}].
+ # Empty list -> empty. A non-text block (image/audio/tool) is real
+ # content; only flag when every text block is blank and no such block
+ # exists (an image-only turn is valid).
+ if len(value) == 0:
+ return True
+ # No dict blocks at all (e.g. [None], [' ']) -> malformed/empty.
+ dict_blocks = [item for item in value if isinstance(item, dict)]
+ if not dict_blocks:
+ return True
+ non_text_blocks = [item for item in dict_blocks if item.get("type") != "text"]
+ if non_text_blocks:
+ return False
+ text_values = [
+ item.get("text") for item in dict_blocks if item.get("type") == "text"
+ ]
+ if text_values and all(
+ t is None
+ or (
+ isinstance(t, str)
+ and not t.strip().strip("\ufeff\u200b\u200c\u200d\u2060").strip()
+ )
+ for t in text_values
+ ):
+ return True
+ return False
+
+
+def _classify_empty(value) -> str:
+ """Return a human-readable label for why this value is considered empty."""
+ if value is None:
+ return "None"
+ if isinstance(value, str):
+ if len(value) == 0:
+ return "empty_string"
+ # Only-whitespace or only-invisible (BOM/zero-width) strings render empty.
+ if not value.strip().strip("\ufeff\u200b\u200c\u200d\u2060").strip():
+ return "whitespace_only"
+ if isinstance(value, list):
+ # Mirrors the VLM/OpenAI content-block handling in is_none_or_empty.
+ if len(value) == 0:
+ return "empty_list"
+ return "empty_vlm_content"
+ return "valid" # should not reach here if is_none_or_empty was True
+
+
+# ---------------------------------------------------------------------------
+# Alpaca detection
+# ---------------------------------------------------------------------------
+
+
+def find_none_alpaca(dataset: Dataset) -> dict:
+ """
+ Scan alpaca dataset for None/empty instruction or output fields.
+ Returns stats dict with a detailed 'findings' list.
+ """
+ stats = {
+ "total_rows": len(dataset),
+ "none_instruction": 0,
+ "none_output": 0,
+ "bad_row_indices": [],
+ "findings": [], # [{row, field, value_type, raw_value}, ...]
+ }
+
+ for i, row in enumerate(dataset):
+ bad = False
+ for field in ("instruction", "output"):
+ val = row.get(field)
+ if is_none_or_empty(val):
+ stats[f"none_{field}"] = stats.get(f"none_{field}", 0) + 1
+ bad = True
+ stats["findings"].append(
+ {
+ "row_index": i,
+ "field": field,
+ "value_type": _classify_empty(val),
+ "raw_value": repr(val),
+ }
+ )
+ if bad:
+ stats["bad_row_indices"].append(i)
+
+ return stats
+
+
+# ---------------------------------------------------------------------------
+# ChatML / conversational detection
+# ---------------------------------------------------------------------------
+
+
+def find_none_chatml(dataset: Dataset, col: str = None) -> dict:
+ """
+ Scan chatml/sharegpt/gptoss dataset for turns with None/empty content.
+ Auto-detects the conversation column if col=None.
+
+ Returns a stats dict that includes a complete 'findings' list - one entry
+ per bad turn with row_index, turn_index, role, value_type, and raw_value.
+ """
+ if col is None:
+ # Reuse _probe_conversation so the all_corrupt path is handled here too.
+ _cinfo = _probe_conversation(dataset)
+ if _cinfo is not None:
+ col = _cinfo["column"]
+
+ if col is None or col not in dataset.column_names:
+ raise ValueError(
+ f"No conversation column found. "
+ f"Expected one of {CONVERSATION_COLUMNS}, got columns: {dataset.column_names}"
+ )
+
+ stats = {
+ "total_rows": len(dataset),
+ "column": col,
+ "rows_with_none_turns": 0,
+ "total_none_turns": 0,
+ "none_by_role": {}, # role -> count of None turns
+ "none_by_type": {}, # "None" | "empty_string" | "whitespace_only" -> count
+ "rows_all_none": 0, # rows where every turn is bad
+ "bad_row_indices": [], # every row index that has at least one bad turn
+ "findings": [], # detailed per-turn list
+ }
+
+ for i, row in enumerate(dataset):
+ conversation = row[col]
+ if not isinstance(conversation, list):
+ # Non-list conversation: unusable for training, flag as bad.
+ vtype = "None" if conversation is None else "invalid_type"
+ stats["bad_row_indices"].append(i)
+ stats["rows_with_none_turns"] += 1
+ stats["total_none_turns"] += 1
+ stats["rows_all_none"] += 1
+ stats["none_by_role"]["unknown"] = (
+ stats["none_by_role"].get("unknown", 0) + 1
+ )
+ stats["none_by_type"][vtype] = stats["none_by_type"].get(vtype, 0) + 1
+ stats["findings"].append(
+ {
+ "row_index": i,
+ "turn_index": 0,
+ "role": "unknown",
+ "value_type": vtype,
+ "raw_value": repr(conversation),
+ }
+ )
+ continue
+
+ if len(conversation) == 0:
+ # Zero-turn conversation: flag so it does not scan as clean.
+ stats["bad_row_indices"].append(i)
+ stats["rows_with_none_turns"] += 1
+ stats["total_none_turns"] += 1
+ stats["rows_all_none"] += 1
+ stats["none_by_role"]["unknown"] = (
+ stats["none_by_role"].get("unknown", 0) + 1
+ )
+ stats["none_by_type"]["empty_conversation"] = (
+ stats["none_by_type"].get("empty_conversation", 0) + 1
+ )
+ stats["findings"].append(
+ {
+ "row_index": i,
+ "turn_index": 0,
+ "role": "unknown",
+ "value_type": "empty_conversation",
+ "raw_value": "[]",
+ }
+ )
+ continue
+
+ row_findings = []
+ for turn_idx, turn in enumerate(conversation):
+ # Non-dict turn - record it rather than crash or silently skip.
+ if not isinstance(turn, dict):
+ row_findings.append(
+ {
+ "row_index": i,
+ "turn_index": turn_idx,
+ "role": "unknown",
+ "value_type": "None" if turn is None else "invalid_type",
+ "raw_value": repr(turn),
+ }
+ )
+ stats["none_by_role"]["unknown"] = (
+ stats["none_by_role"].get("unknown", 0) + 1
+ )
+ vtype = "None" if turn is None else "invalid_type"
+ stats["none_by_type"][vtype] = stats["none_by_type"].get(vtype, 0) + 1
+ continue
+ # Explicit None check so falsy roles (0, "", False) are kept, not
+ # collapsed to "unknown".
+ r = turn.get("role")
+ if r is None:
+ r = turn.get("from")
+ if r is None:
+ role = "unknown"
+ elif isinstance(r, str):
+ role = r
+ else:
+ role = str(r)
+ # Pick the content key: from+value -> value (ShareGPT, even if role is
+ # also set); role -> content (or value); from only -> value (None when
+ # missing, so it is flagged); neither -> content then value.
+ if "from" in turn and "value" in turn:
+ content = turn.get("value")
+ elif "role" in turn:
+ content = (
+ turn.get("content") if "content" in turn else turn.get("value")
+ )
+ elif "from" in turn:
+ content = turn.get("value")
+ else:
+ content = (
+ turn.get("content") if "content" in turn else turn.get("value")
+ )
+ # Assistant tool-call turns carry empty content + tool_calls and are
+ # valid; the exemption is assistant-only.
+ if is_none_or_empty(content) and not (
+ role == "assistant" and turn.get("tool_calls")
+ ):
+ vtype = _classify_empty(content)
+ row_findings.append(
+ {
+ "row_index": i,
+ "turn_index": turn_idx,
+ "role": role,
+ "value_type": vtype,
+ "raw_value": repr(content),
+ }
+ )
+ stats["none_by_role"][role] = stats["none_by_role"].get(role, 0) + 1
+ stats["none_by_type"][vtype] = stats["none_by_type"].get(vtype, 0) + 1
+
+ if row_findings:
+ stats["rows_with_none_turns"] += 1
+ stats["total_none_turns"] += len(row_findings)
+ stats["bad_row_indices"].append(i)
+ stats["findings"].extend(row_findings)
+
+ if len(row_findings) == len(conversation):
+ stats["rows_all_none"] += 1
+
+ return stats
+
+
+# ---------------------------------------------------------------------------
+# Convenience wrappers per format (all delegate to the same scan logic)
+# ---------------------------------------------------------------------------
+
+
+def find_none_sharegpt(dataset: Dataset, col: str = None) -> dict:
+ """ShareGPT uses 'from'/'value' keys - same scan logic handles both."""
+ if col is None:
+ # ShareGPT lives in 'conversations'; probe only that column so a corrupt
+ # one is still scanned, not replaced by a healthy 'messages' (P1 fix).
+ conv_info = _probe_conversation(dataset, candidates = ("conversations",))
+ if conv_info is None:
+ raise ValueError(
+ f"No valid conversation column found in {dataset.column_names}. "
+ "Expected a 'conversations' column with 'from'/'value' or 'role'/'content' turn keys."
+ )
+ col = conv_info["column"]
+ return find_none_chatml(dataset, col = col)
+
+
+def find_none_gptoss(dataset: Dataset, col: str = None) -> dict:
+ """gptoss: role/content plus optional thinking/tool_calls. Only content checked."""
+ if col is None:
+ # gptoss lives in 'messages': target it whenever present (even if
+ # corrupt), and fall back to 'conversations' only if 'messages' is absent.
+ if "messages" in dataset.column_names:
+ conv_info = _probe_conversation(dataset, candidates = ("messages",))
+ else:
+ conv_info = _probe_conversation(dataset, candidates = ("conversations",))
+ if conv_info is None:
+ raise ValueError(
+ f"No valid conversation column found in {dataset.column_names}. "
+ "Expected a 'messages' or 'conversations' column with 'role'/'content' turn keys."
+ )
+ col = conv_info["column"]
+ return find_none_chatml(dataset, col = col)
+
+
+# ---------------------------------------------------------------------------
+# Format registry - first match wins; detect_format() auto-scales.
+# Each entry: name (label/--format value), match(dataset, conv_info) -> bool,
+# scan (find_none_* function). Put specific formats before generalisations
+# (gptoss before chatml, since gptoss is chatml with a 'developer' role).
+# To add a format: write find_none_<name>() (or reuse find_none_chatml) and
+# append an entry; detect_format(), --format, and scan_dataset() pick it up.
+# ---------------------------------------------------------------------------
+
+FORMAT_REGISTRY = [
+ {
+ "name": "alpaca",
+ # instruction/output present and no usable chat column: either none
+ # exists, or the only one is fully corrupt (e.g. a stray all-None or
+ # metadata `messages` column). A healthy chat column falls through to
+ # the conversational scanners below.
+ "match": lambda ds, conv: (
+ {"instruction", "output"}.issubset(ds.column_names)
+ and (conv is None or conv.get("all_corrupt"))
+ ),
+ "scan": find_none_alpaca,
+ },
+ {
+ "name": "gptoss",
+ "match": lambda ds, conv: (
+ conv is not None
+ and {"role", "content"} <= conv["turn_keys"]
+ and "developer" in conv["roles"]
+ ),
+ "scan": find_none_gptoss,
+ },
+ {
+ "name": "sharegpt",
+ "match": lambda ds, conv: (
+ conv is not None and {"from", "value"} <= conv["turn_keys"]
+ ),
+ "scan": find_none_sharegpt,
+ },
+ {
+ "name": "chatml",
+ "match": lambda ds, conv: (
+ conv is not None
+ and (
+ {"role", "content"} <= conv["turn_keys"]
+ # all_corrupt: column found but every row malformed; require
+ # has_plausible_turns so scalar/string columns are not chatml.
+ or (conv.get("all_corrupt") and conv.get("has_plausible_turns"))
+ )
+ ),
+ "scan": find_none_chatml,
+ },
+]
+
+# Derived list of known format names (used by CLI --format choices).
+FORMAT_NAMES = [entry["name"] for entry in FORMAT_REGISTRY]
+
+# Documented aliases accepted by both the Python API and the CLI.
+FORMAT_ALIASES = {"gpt-oss": "gptoss"}
+
+
+def detect_format(dataset: Dataset) -> str:
+ """
+ Auto-detect dataset format by probing columns and turn structure.
+
+ Returns one of the format names in FORMAT_REGISTRY, or 'unknown'.
+ Walks the registry in order; first match wins.
+ """
+ conv_info = _probe_conversation(dataset)
+ for entry in FORMAT_REGISTRY:
+ if entry["match"](dataset, conv_info):
+ return entry["name"]
+ return "unknown"
+
+
+def get_scanner(fmt: str):
+ """Return the scanner function for a format name, or None if unknown."""
+ for entry in FORMAT_REGISTRY:
+ if entry["name"] == fmt:
+ return entry["scan"]
+ return None
+
+
+def scan_dataset(dataset: Dataset, fmt: str = "auto") -> dict:
+ """
+ One-liner: detect format (if 'auto') and scan for None/empty content.
+
+ Returns the stats dict with an added 'format' key.
+ Raises ValueError if the format is unknown or unsupported.
+ """
+ # Reject a DatasetDict / IterableDatasetDict (load_dataset without split):
+ # its column_names is a split map and would yield a confusing "unknown
+ # format". Check both (IterableDatasetDict is not a DatasetDict subclass);
+ # import locally so this module never hard-requires those symbols.
+ _dict_types = []
+ try:
+ from datasets import DatasetDict as _DatasetDict
+
+ _dict_types.append(_DatasetDict)
+ except ImportError:
+ pass
+ try:
+ from datasets import IterableDatasetDict as _IterableDatasetDict
+
+ _dict_types.append(_IterableDatasetDict)
+ except ImportError:
+ pass
+ if _dict_types and isinstance(dataset, tuple(_dict_types)):
+ raise ValueError(
+ "scan_dataset requires a single Dataset split, not a DatasetDict. "
+ f"Available splits: {list(dataset.keys())}. "
+ "Pass dataset[<split>] or use load_dataset(..., split='train')."
+ )
+ # Streaming IterableDataset has no len()/column_names; give a clear error
+ # instead of a confusing TypeError downstream.
+ try:
+ from datasets import IterableDataset as _IterableDataset
+
+ if isinstance(dataset, _IterableDataset):
+ raise ValueError(
+ "scan_dataset requires a materialized Dataset, not an IterableDataset. "
+ "Load without streaming=True, or materialize a slice first: "
+ "Dataset.from_list(list(dataset.take(N)))."
+ )
+ except ImportError:
+ pass
+ fmt = FORMAT_ALIASES.get(fmt, fmt)
+ was_auto = fmt == "auto"
+ # Zero-row dataset: return a trivially clean stats dict.
+ if was_auto and len(dataset) == 0:
+ return {
+ "format": "unknown",
+ "total_rows": 0,
+ "findings": [],
+ "bad_row_indices": [],
+ }
+ # Always probe so detection and column selection share one scan pass.
+ conv_info = _probe_conversation(dataset)
+ if was_auto:
+ fmt = "unknown"
+ for entry in FORMAT_REGISTRY:
+ if entry["match"](dataset, conv_info):
+ fmt = entry["name"]
+ break
+ # No format matched: return clean stats (format="unknown") rather than
+ # raise, so callers can branch on stats["format"].
+ if fmt == "unknown":
+ return {
+ "format": "unknown",
+ "total_rows": len(dataset),
+ "findings": [],
+ "bad_row_indices": [],
+ }
+ scanner = get_scanner(fmt)
+ if scanner is None:
+ raise ValueError(f"Unknown or unsupported format: '{fmt}'")
+ # Column forwarding: on auto-detect pass the probed column (already the best
+ # choice). On an explicit format let that scanner pick its own column, so
+ # e.g. fmt='sharegpt' always scans 'conversations', not 'messages' (P1 fix);
+ # gptoss has its own messages-first rule. alpaca never takes a column.
+ use_probed_col = conv_info is not None and fmt != "alpaca" and was_auto
+ if use_probed_col:
+ stats = scanner(dataset, col = conv_info["column"])
+ else:
+ stats = scanner(dataset)
+ stats["format"] = fmt
+ return stats
+
+
+# ---------------------------------------------------------------------------
+# Report printing
+# ---------------------------------------------------------------------------
+
+
+def _print_summary_header(stats: dict, fmt: str) -> bool:
+ """Print the top-level stats block (shared by all report modes). Returns True if findings exist."""
+ total = stats["total_rows"]
+ findings = stats.get("findings", [])
+
+ print(f"\n{'=' * 64}")
+ print(f" None / Empty Detection Report")
+ print(f"{'=' * 64}")
+ print(f" Format: {fmt}")
+ print(f" Total rows: {total}")
+
+ if not findings:
+ if fmt == "unknown":
+ print(f" Result: NOT SCANNED -- format could not be detected")
+ else:
+ print(f" Result: CLEAN -- no None or empty values found")
+ print(f"{'=' * 64}")
+ return False
+
+ if fmt == "alpaca":
+ bad_rows = len(stats.get("bad_row_indices", []))
+ print(f" Rows with Nones: {bad_rows} / {total}")
+ print(f" None instruction: {stats.get('none_instruction', 0)}")
+ print(f" None output: {stats.get('none_output', 0)}")
+ else:
+ col = stats.get("column", "?")
+ print(f" Column: {col}")
+ print(f" Rows with bad turns: {stats['rows_with_none_turns']} / {total}")
+ print(f" Total bad turns: {len(findings)}")
+ print(f" By type: {stats.get('none_by_type', {})}")
+ print(f" By role: {stats.get('none_by_role', {})}")
+ rows_all = stats.get("rows_all_none", 0)
+ if rows_all:
+ print(f" Rows ALL bad: {rows_all} (every turn is None/empty)")
+
+ # Rows with no Nones - compute the count directly instead of allocating a
+ # full set of row indices, which OOMs on large (10M+ row) datasets.
+ bad_indices = set(stats.get("bad_row_indices", []))
+ clean_count = total - len(bad_indices)
+ if 0 < clean_count <= 20:
+ clean_indices = [i for i in range(total) if i not in bad_indices]
+ print(f" Rows with no Nones: {clean_count} / {total} {clean_indices}")
+ else:
+ print(f" Rows with no Nones: {clean_count} / {total}")
+
+ print(f"{'=' * 64}")
+ return True
+
+
+def print_report(stats: dict, fmt: str, summary_only: bool = False):
+ """Print a human-readable summary, optionally with full findings list."""
+ has_findings = _print_summary_header(stats, fmt)
+ if not has_findings or summary_only:
+ return
+
+ findings = stats.get("findings", [])
+ print(f"\n {'-' * 60}")
+ print(f" Findings ({len(findings)} total):")
+ print(f" {'-' * 60}")
+
+ for f in findings:
+ if fmt == "alpaca":
+ print(
+ f" row {f['row_index']:>5d} "
+ f"field={f['field']:<12s} "
+ f"type={f['value_type']:<16s} "
+ f"raw={f['raw_value']}"
+ )
+ else:
+ print(
+ f" row {f['row_index']:>5d} "
+ f"turn {f['turn_index']} "
+ f"role={str(f['role']):<12s} "
+ f"type={f['value_type']:<16s} "
+ f"raw={f['raw_value']}"
+ )
+
+ print(f"{'=' * 64}")
+
+
+def show_row(dataset: Dataset, row_indices: list[int], fmt: str, col: str = None):
+ """Print the full contents of specific rows for inspection.
+
+ Used by test_codex_fixes.py to verify row rendering behaviour.
+ Not part of the production API.
+ """
+ if col is None:
+ for candidate in ("messages", "conversations", "texts"):
+ if candidate in dataset.column_names:
+ col = candidate
+ break
+
+ for ri in row_indices:
+ if ri < 0 or ri >= len(dataset):
+ print(f"\n [ERROR] Row {ri} out of range (0-{len(dataset)-1})")
+ continue
+
+ row = dataset[ri]
+ print(f"\n{'=' * 64}")
+ print(f" Row {ri}")
+ print(f"{'=' * 64}")
+
+ # Print non-conversation columns. For alpaca, skip the fields the
+ # alpaca block below prints with status markers (avoid double render).
+ _ALPACA_FIELDS = {"instruction", "input", "output"}
+ for key in dataset.column_names:
+ if key == col:
+ continue
+ if fmt == "alpaca" and key in _ALPACA_FIELDS:
+ continue
+ val = row[key]
+ if isinstance(val, str) and len(val) > 120:
+ val = val[:120] + "..."
+ print(f" {key}: {val}")
+
+ if fmt == "alpaca":
+ for field in ("instruction", "input", "output"):
+ val = row.get(field)
+ status = " [NONE]" if is_none_or_empty(val) else ""
+ if val and len(str(val)) > 200:
+ val = str(val)[:200] + "..."
+ print(f" {field}: {val}{status}")
+ elif col:
+ conversation = row[col]
+ if isinstance(conversation, list):
+
+ def _is_bad_turn(t):
+ if not isinstance(t, dict):
+ return True
+ # Mirror scanner logic: from+value wins, then role, then from alone.
+ if "from" in t and "value" in t:
+ c = t.get("value")
+ elif "role" in t:
+ c = t.get("content") if "content" in t else t.get("value")
+ elif "from" in t:
+ c = t.get("value")
+ else:
+ c = t.get("content") if "content" in t else t.get("value")
+ # Mirror scanner logic: tool_calls exemption is assistant-only;
+ # other roles with empty content + tool_calls are still bad.
+ r = t.get("role") if t.get("role") is not None else t.get("from")
+ if is_none_or_empty(c) and not (
+ str(r) == "assistant" and t.get("tool_calls")
+ ):
+ return True
+ return False
+
+ none_count = sum(1 for t in conversation if _is_bad_turn(t))
+ print(f" {col}: {len(conversation)} turns ({none_count} None)")
+ print(f" {'-' * 60}")
+ for i, turn in enumerate(conversation):
+ # Non-dict turn - can't extract role or content normally.
+ if not isinstance(turn, dict):
+ label = "None" if turn is None else "invalid_type"
+ print(f" [{i:>3d}] {'unknown':<12s} [{label}] << NONE")
+ continue
+ r = turn.get("role")
+ if r is None:
+ r = turn.get("from")
+ role = "?" if r is None else str(r)
+ # Mirror scanner logic: from+value wins, then role, then from alone.
+ if "from" in turn and "value" in turn:
+ content = turn.get("value")
+ elif "role" in turn:
+ content = (
+ turn.get("content")
+ if "content" in turn
+ else turn.get("value")
+ )
+ elif "from" in turn:
+ content = turn.get("value")
+ else:
+ content = (
+ turn.get("content")
+ if "content" in turn
+ else turn.get("value")
+ )
+ if is_none_or_empty(content) and not (
+ role == "assistant" and turn.get("tool_calls")
+ ):
+ status = " << NONE"
+ else:
+ status = ""
+ if content is None:
+ preview = "None"
+ else:
+ preview_str = str(content) # cast: content may not be a string
+ if len(preview_str) > 150:
+ preview = preview_str[:150].replace("\n", "\\n") + "..."
+ else:
+ preview = preview_str.replace("\n", "\\n")
+ print(f" [{i:>3d}] {role:<12s} {preview}{status}")
+
+ print(f"{'=' * 64}")
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ import argparse
+ import os
+ import sys
+
+ parser = argparse.ArgumentParser(
+ prog = "dataset_none_detect",
+ description = "Scan a HuggingFace dataset for None/empty content turns.",
+ formatter_class = argparse.RawDescriptionHelpFormatter,
+ epilog = """
+examples:
+ python dataset_none_detect.py org/my-dataset
+ python dataset_none_detect.py org/my-dataset --split train
+ python dataset_none_detect.py org/my-dataset --format sharegpt
+ python dataset_none_detect.py org/my-dataset --summary-only
+ python dataset_none_detect.py org/my-dataset --token hf_...
+ """,
+ )
+ parser.add_argument(
+ "dataset", help = "HuggingFace dataset repo id (e.g. org/my-dataset)"
+ )
+ parser.add_argument(
+ "--split", default = "train", help = "Dataset split to load (default: train)"
+ )
+ parser.add_argument(
+ "--format",
+ default = "auto",
+ choices = ["auto"] + FORMAT_NAMES + list(FORMAT_ALIASES),
+ help = "Force a specific format instead of auto-detecting (default: auto). "
+ "Documented aliases (e.g. 'gpt-oss' for 'gptoss') are also accepted.",
+ )
+ parser.add_argument(
+ "--summary-only",
+ action = "store_true",
+ help = "Print summary header only - skip the per-turn findings list",
+ )
+ parser.add_argument(
+ "--token",
+ default = os.environ.get("HF_TOKEN"),
+ help = (
+ "HuggingFace API token for private datasets (default: $HF_TOKEN). "
+ "Prefer setting $HF_TOKEN; passing --token on the command line "
+ "exposes it in process listings."
+ ),
+ )
+ args = parser.parse_args()
+
+ try:
+ from datasets import load_dataset
+ except ImportError:
+ print(
+ "Error: 'datasets' package not found. Install with: pip install datasets",
+ file = sys.stderr,
+ )
+ sys.exit(1)
+
+ print(f"Loading {args.dataset!r} (split={args.split!r})...")
+ try:
+ ds = load_dataset(args.dataset, split = args.split, token = args.token)
+ except Exception as exc:
+ # Some `datasets` / `requests` versions include the Authorization
+ # header in exception messages. Redact the token before printing.
+ msg = str(exc)
+ if args.token:
+ msg = msg.replace(args.token, "hf_***REDACTED***")
+ print(f"Error loading dataset: {msg}", file = sys.stderr)
+ sys.exit(1)
+
+ print(f"Loaded {len(ds)} rows, columns: {ds.column_names}")
+
+ try:
+ stats = scan_dataset(ds, fmt = args.format)
+ except ValueError as exc:
+ print(f"Error: {exc}", file = sys.stderr)
+ sys.exit(1)
+
+ print_report(stats, stats["format"], summary_only = args.summary_only)
diff --git a/tests/utils/generate_dataset_with_none.py b/tests/utils/generate_dataset_with_none.py
new file mode 100644
index 00000000000..71d228963a6
--- /dev/null
+++ b/tests/utils/generate_dataset_with_none.py
@@ -0,0 +1,265 @@
+"""
+generate_dataset_with_none.py
+
+Generates a small synthetic dataset that intentionally contains None/empty
+turns so dataset_none_detect.py can be verified end-to-end.
+
+Produces three formats:
+ - chatml (messages column, role/content turns)
+ - sharegpt (conversations column, from/value turns)
+ - alpaca (instruction/output columns)
+
+Each format gets ~20 rows; roughly half have at least one bad turn.
+
+No heavy dependencies -- just `datasets`.
+"""
+
+from datasets import Dataset
+
+# ---------------------------------------------------------------------------
+# ChatML (messages, role/content)
+# ---------------------------------------------------------------------------
+
+# NOTE: pyarrow requires uniform types in a column, so rows with messages=None
+# or messages="not a list" (P1 cases) live in a SEPARATE dataset (see
+# make_chatml_p1_dataset below) so pyarrow can infer the column type correctly.
+
+_CHATML_ROWS = [
+ # clean rows
+ {
+ "messages": [
+ {"role": "user", "content": "What is 2+2?"},
+ {"role": "assistant", "content": "4"},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "Name a colour."},
+ {"role": "assistant", "content": "Blue."},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "system", "content": "You are helpful."},
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello!"},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "Tell me a joke."},
+ {"role": "assistant", "content": "Why did the chicken cross the road?"},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "Capital of France?"},
+ {"role": "assistant", "content": "Paris."},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "Count to 3."},
+ {"role": "assistant", "content": "1, 2, 3."},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "What is Python?"},
+ {"role": "assistant", "content": "A programming language."},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "Translate 'hello' to Spanish."},
+ {"role": "assistant", "content": "Hola."},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "What is gravity?"},
+ {"role": "assistant", "content": "A fundamental force."},
+ ]
+ },
+ {
+ "messages": [
+ {"role": "user", "content": "Who wrote Hamlet?"},
+ {"role": "assistant", "content": "Shakespeare."},
+ ]
+ },
+ # bad rows — None/empty turn content (all messages values are lists so pyarrow is happy)
+ {
+ "messages": [
+ {"role": "user", "content": None},
+ {"role": "assistant", "content": "Sure!"},
+ ]
+ }, # None content
+ {
+ "messages": [
+ {"role": "user", "content": ""},
+ {"role": "assistant", "content": "OK."},
+ ]
+ }, # empty string
+ {
+ "messages": [
+ {"role": "user", "content": " "},
+ {"role": "assistant", "content": "Got it."},
+ ]
+ }, # whitespace only
+ {
+ "messages": [
+ {"role": "user", "content": "Hello"},
+ {"role": "assistant", "content": None},
+ ]
+ }, # None assistant
+ {
+ "messages": [
+ {"role": "user", "content": None},
+ {"role": "assistant", "content": None},
+ ]
+ }, # both None
+ {
+ "messages": [
+ {"role": "user", "content": ""},
+ {"role": "assistant", "content": ""},
+ ]
+ }, # both empty
+ {
+ "messages": [
+ {"role": "user", "content": "Anything?"},
+ {"role": "assistant", "content": " \t "},
+ ]
+ }, # tab whitespace
+ {
+ "messages": [None, {"role": "assistant", "content": "Reply"}]
+ }, # None turn element
+]
+
+# P1 test rows: messages is None or non-list.
+# Stored as a plain list of dicts rather than an HF Dataset because pyarrow
+# cannot mix list and non-list values in the same column. The test runner
+# uses a lightweight mock to exercise find_none_chatml directly.
+_CHATML_P1_ROWS = [
+ {"messages": None}, # whole column None
+ {"messages": "not a list"}, # wrong type
+]
+
+
+def make_chatml_p1_rows() -> list:
+ """Return the raw P1 rows (not an HF Dataset) for direct mock testing."""
+ return list(_CHATML_P1_ROWS)
+
+
+# ---------------------------------------------------------------------------
+# ShareGPT (conversations, from/value)
+# ---------------------------------------------------------------------------
+
+_SHAREGPT_ROWS = [
+ # clean
+ {
+ "conversations": [
+ {"from": "human", "value": "Hello"},
+ {"from": "gpt", "value": "Hi there!"},
+ ]
+ },
+ {
+ "conversations": [
+ {"from": "human", "value": "What time is it?"},
+ {"from": "gpt", "value": "I don't know."},
+ ]
+ },
+ {
+ "conversations": [
+ {"from": "human", "value": "Good morning"},
+ {"from": "gpt", "value": "Good morning!"},
+ ]
+ },
+ {
+ "conversations": [
+ {"from": "human", "value": "Tell me about AI."},
+ {"from": "gpt", "value": "AI stands for Artificial Intelligence."},
+ ]
+ },
+ {
+ "conversations": [
+ {"from": "human", "value": "Bye"},
+ {"from": "gpt", "value": "Goodbye!"},
+ ]
+ },
+ # bad
+ {
+ "conversations": [
+ {"from": "human", "value": None},
+ {"from": "gpt", "value": "Sure!"},
+ ]
+ },
+ {
+ "conversations": [
+ {"from": "human", "value": ""},
+ {"from": "gpt", "value": "OK."},
+ ]
+ },
+ {
+ "conversations": [
+ {"from": "human", "value": "Hello"},
+ {"from": "gpt", "value": None},
+ ]
+ },
+ {"conversations": None}, # P1: whole column is None
+ {"conversations": [None, {"from": "gpt", "value": "Hi"}]},
+]
+
+# ---------------------------------------------------------------------------
+# Alpaca (instruction / output columns)
+# ---------------------------------------------------------------------------
+
+_ALPACA_ROWS = [
+ # clean
+ {
+ "instruction": "Summarise this text.",
+ "input": "The sky is blue.",
+ "output": "The sky is blue.",
+ },
+ {"instruction": "Translate to French.", "input": "Hello", "output": "Bonjour"},
+ {"instruction": "What is 10*10?", "input": "", "output": "100"},
+ {
+ "instruction": "Name the planets.",
+ "input": "",
+ "output": "Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune",
+ },
+ {
+ "instruction": "Write a haiku.",
+ "input": "",
+ "output": "Old pond — / frog jumps in / water's sound",
+ },
+ # bad
+ {"instruction": None, "input": "", "output": "Some output"},
+ {"instruction": "", "input": "", "output": "Some output"},
+ {"instruction": "Valid instruction", "input": "", "output": None},
+ {"instruction": None, "input": "", "output": None},
+ {"instruction": " ", "input": "", "output": ""},
+]
+
+
+def make_chatml_dataset() -> Dataset:
+ return Dataset.from_list(_CHATML_ROWS)
+
+
+def make_sharegpt_dataset() -> Dataset:
+ return Dataset.from_list(_SHAREGPT_ROWS)
+
+
+def make_alpaca_dataset() -> Dataset:
+ return Dataset.from_list(_ALPACA_ROWS)
+
+
+if __name__ == "__main__":
+ print("Synthetic dataset sizes:")
+ print(
+ f" chatml: {len(_CHATML_ROWS)} rows (+ {len(_CHATML_P1_ROWS)} P1 mock rows)"
+ )
+ print(f" sharegpt: {len(_SHAREGPT_ROWS)} rows")
+ print(f" alpaca: {len(_ALPACA_ROWS)} rows")
+ print(
+ "\nImport make_chatml_dataset, make_sharegpt_dataset, make_alpaca_dataset, make_chatml_p1_rows."
+ )
diff --git a/tests/utils/run_none_detect_tests.py b/tests/utils/run_none_detect_tests.py
new file mode 100644
index 00000000000..8fc31faf04b
--- /dev/null
+++ b/tests/utils/run_none_detect_tests.py
@@ -0,0 +1,748 @@
+"""
+run_none_detect_tests.py
+
+Runs dataset_none_detect.py against:
+ 1. Synthetic datasets (chatml, sharegpt, alpaca) with deliberately injected Nones
+ 2. peteromallet/dataclaw-peteromallet (HuggingFace)
+ 3. peteromallet/my-personal-codex-data (HuggingFace)
+
+Writes a detailed log to tests/logs/none_detect_results.log
+
+Usage (from repo root, with venv active):
+ python tests/utils/run_none_detect_tests.py
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import traceback
+from datetime import datetime
+from io import StringIO
+from pathlib import Path
+
+# Allow running from repo root without install.
+# Insert the datasets directory directly so dataset_none_detect is imported
+# as a top-level module, bypassing utils/datasets/__init__.py which pulls in
+# torch, fastapi, and other heavy studio deps not needed for this utility.
+REPO_ROOT = Path(__file__).resolve().parent.parent.parent
+sys.path.insert(0, str(REPO_ROOT / "studio" / "backend" / "utils" / "datasets"))
+
+from dataset_none_detect import (
+ find_none_chatml,
+ print_report,
+ scan_dataset,
+)
+
+LOG_DIR = REPO_ROOT / "tests" / "logs"
+LOG_DIR.mkdir(parents = True, exist_ok = True)
+LOG_PATH = LOG_DIR / "none_detect_results.log"
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+class Tee:
+ """Write to both stdout and a file simultaneously."""
+
+ def __init__(self, file):
+ self.file = file
+ self.stdout = sys.stdout
+
+ def write(self, data):
+ self.stdout.write(data)
+ self.file.write(data)
+
+ def flush(self):
+ self.stdout.flush()
+ self.file.flush()
+
+
+def section(title: str):
+ line = "=" * 70
+ print(f"\n{line}")
+ print(f" {title}")
+ print(f"{line}")
+
+
+def run_scan(dataset, label: str, fmt: str = "auto") -> dict | None:
+ print(f"\n--- Scanning: {label} (fmt={fmt}) ---")
+ try:
+ stats = scan_dataset(dataset, fmt = fmt)
+ print_report(stats, stats["format"])
+ return stats
+ except Exception as exc:
+ print(f" [ERROR] {exc}")
+ traceback.print_exc()
+ return None
+
+
+def assert_bad_rows(stats: dict, expected_min: int, label: str):
+ bad = len(stats.get("bad_row_indices", []))
+ status = "PASS" if bad >= expected_min else "FAIL"
+ print(f" [{status}] {label}: found {bad} bad rows (expected >= {expected_min})")
+ return status == "PASS"
+
+
+def assert_exact_recall(stats: dict, expected_bad: set, label: str):
+ """Every injected bad row index must appear in bad_row_indices — no misses."""
+ actual_bad = set(stats.get("bad_row_indices", []))
+ missed = expected_bad - actual_bad
+ all_caught = len(missed) == 0
+ status = "PASS" if all_caught else "FAIL"
+ caught_count = len(expected_bad) - len(missed)
+ print(
+ f" [{status}] {label}: exact recall — "
+ f"{caught_count}/{len(expected_bad)} injected bad rows caught",
+ end = "",
+ )
+ if missed:
+ print(f" (missed rows: {sorted(missed)})")
+ else:
+ print()
+ return all_caught
+
+
+# ---------------------------------------------------------------------------
+# 1. Synthetic datasets
+# ---------------------------------------------------------------------------
+
+
+# ---------------------------------------------------------------------------
+# Minimal mock so find_none_chatml can be called with hand-crafted rows that
+# pyarrow can't represent (e.g. messages=None, messages="not a list").
+# ---------------------------------------------------------------------------
+
+
+class _MockDataset:
+ """Behaves like an HF Dataset for iteration, len(), and index access."""
+
+ def __init__(self, rows: list, columns: list):
+ self.column_names = columns
+ self._rows = rows
+
+ def __len__(self):
+ return len(self._rows)
+
+ def __iter__(self):
+ return iter(self._rows)
+
+ def __getitem__(self, idx):
+ """Support dataset[i] (int) and dataset[i][col] patterns used by _probe_conversation."""
+ return self._rows[idx]
+
+
+def test_p1_fix():
+ """Verify that find_none_chatml records rows where messages is None or non-list."""
+ section("P1 Fix Verification — non-list conversation column values")
+
+ sys.path.insert(0, str(REPO_ROOT / "tests" / "utils"))
+ from generate_dataset_with_none import make_chatml_p1_rows
+
+ p1_rows = make_chatml_p1_rows()
+ mock_ds = _MockDataset(p1_rows, ["messages"])
+
+ print(f" Rows under test: {p1_rows}")
+ stats = find_none_chatml(mock_ds, col = "messages")
+ print_report(stats, "chatml")
+
+ expected_bad = set(range(len(p1_rows)))
+ actual_bad = set(stats.get("bad_row_indices", []))
+ all_caught = expected_bad.issubset(actual_bad)
+ print(
+ f" [{'PASS' if all_caught else 'FAIL'}] P1 fix: all {len(expected_bad)} non-list rows caught"
+ )
+
+ for row in stats.get("findings", []):
+ vtype = row.get("value_type", "?")
+ raw = row.get("raw_value", "?")
+ print(f" row {row['row_index']}: value_type={vtype!r} raw={raw}")
+
+ return stats
+
+
+def test_probe_p1_fix():
+ """Verify that scan_dataset(fmt='auto') on a fully-corrupt messages column
+ routes through _probe_conversation's all_corrupt=True path and returns
+ findings rather than raising ValueError."""
+ section("P1 Fix Verification — probe skip on all-corrupt column (auto-detect path)")
+
+ # All 5 rows have messages=None — no dict turn will ever be found in the probe.
+ all_corrupt_rows = [{"messages": None}] * 5
+ mock_ds = _MockDataset(all_corrupt_rows, ["messages"])
+
+ print(f" Rows under test: {len(all_corrupt_rows)} rows all with messages=None")
+ try:
+ stats = scan_dataset(mock_ds, fmt = "auto")
+ print_report(stats, stats.get("format", "?"))
+ bad = len(stats.get("bad_row_indices", []))
+ status = "PASS" if bad == len(all_corrupt_rows) else "FAIL"
+ print(
+ f" [{status}] Probe P1 fix: {bad}/{len(all_corrupt_rows)} all-corrupt rows caught via auto-detect"
+ )
+ return stats
+ except ValueError as exc:
+ print(
+ f" [FAIL] scan_dataset raised ValueError (probe P1 bug NOT fixed): {exc}"
+ )
+ return None
+
+
+def test_probe_string_corrupt():
+ """Verify that a plain-string 'messages' column is NOT classified as chatml.
+ The all_corrupt+has_list_or_none guard (P2 fix) must prevent plain-string
+ columns from triggering the chatml path — scan_dataset should raise
+ ValueError('unknown format') rather than misclassifying as chatml."""
+ section("P2 Fix Verification — plain-string messages not classified as chatml")
+
+ string_rows = [{"messages": "this is a string, not a list"}] * 5
+ mock_ds = _MockDataset(string_rows, ["messages"])
+
+ print(f" Rows under test: {len(string_rows)} rows all with messages='string'")
+ try:
+ stats = scan_dataset(mock_ds, fmt = "auto")
+ fmt = stats.get("format", "?")
+ # Plain strings must NOT be classified as chatml.
+ not_chatml = fmt != "chatml"
+ status = "PASS" if not_chatml else "FAIL"
+ print(
+ f" [{status}] String-corrupt probe: detected fmt={fmt!r} "
+ f"(expected: anything except 'chatml')"
+ )
+ return stats
+ except ValueError as exc:
+ # ValueError (unknown format) is the CORRECT outcome — plain strings
+ # are not a conversation column and should not match any format.
+ print(
+ f" [PASS] String-corrupt probe: scan_dataset raised ValueError (not chatml, as expected): {exc}"
+ )
+ return None
+
+
+def test_explicit_fmt_corrupt():
+ """Verify that scan_dataset(fmt='chatml') on an all-corrupt column returns
+ findings instead of raising ValueError (explicit format + all_corrupt path)."""
+ section("P1 Fix Verification — explicit fmt='chatml' on all-corrupt column")
+
+ all_corrupt_rows = [{"messages": None}] * 4 + [{"messages": "not a list"}] * 3
+ mock_ds = _MockDataset(all_corrupt_rows, ["messages"])
+
+ print(f" Rows under test: {len(all_corrupt_rows)} rows (4×None, 3×string)")
+ try:
+ stats = scan_dataset(mock_ds, fmt = "chatml")
+ print_report(stats, stats.get("format", "?"))
+ bad = len(stats.get("bad_row_indices", []))
+ status = "PASS" if bad == len(all_corrupt_rows) else "FAIL"
+ print(
+ f" [{status}] Explicit-fmt P1 fix: {bad}/{len(all_corrupt_rows)} rows caught with fmt='chatml'"
+ )
+ return stats
+ except ValueError as exc:
+ print(
+ f" [FAIL] scan_dataset raised ValueError (explicit-fmt P1 NOT fixed): {exc}"
+ )
+ return None
+
+
+def test_p2_probe_skips_corrupt_prefers_valid():
+ """P2 fix: probe must continue past a corrupt 'messages' column and find
+ a valid 'conversations' column rather than returning all_corrupt immediately."""
+ section(
+ "P2 Fix Verification — probe continues past corrupt first column to valid second"
+ )
+
+ # messages column is all-None; conversations is a valid ShareGPT column.
+ rows = [
+ {
+ "messages": None,
+ "conversations": [
+ {"from": "human", "value": "Hello"},
+ {"from": "gpt", "value": "Hi!"},
+ ],
+ }
+ ] * 5 + [
+ {
+ "messages": None,
+ "conversations": [
+ {"from": "human", "value": ""},
+ {"from": "gpt", "value": "OK"},
+ ],
+ }
+ ] * 2
+ mock_ds = _MockDataset(rows, ["messages", "conversations"])
+
+ print(
+ f" Rows: {len(rows)} — messages=None, conversations=valid ShareGPT (2 bad value='')"
+ )
+ try:
+ stats = scan_dataset(mock_ds, fmt = "auto")
+ fmt = stats.get("format", "?")
+ col = stats.get("column", "?")
+ bad = len(stats.get("bad_row_indices", []))
+ # Should have detected 'conversations' (sharegpt), not 'messages'.
+ correct_col = col == "conversations"
+ correct_fmt = fmt == "sharegpt"
+ correct_bad = bad == 2
+ status = "PASS" if (correct_col and correct_fmt and correct_bad) else "FAIL"
+ print(
+ f" [{status}] Probe P2 fix: fmt={fmt!r} col={col!r} bad_rows={bad} "
+ f"(expected fmt='sharegpt' col='conversations' bad=2)"
+ )
+ print_report(stats, fmt)
+ return stats
+ except ValueError as exc:
+ print(f" [FAIL] scan_dataset raised ValueError: {exc}")
+ return None
+
+
+def test_p2_explicit_fmt_col_priority():
+ """P2 fix: explicit fmt='sharegpt' must let find_none_sharegpt choose its own
+ column (conversations) rather than being forced onto the probe's column (messages)."""
+ section(
+ "P2 Fix Verification — explicit fmt='sharegpt' respects per-scanner column priority"
+ )
+
+ # messages has valid role/content turns (chatml-ish); conversations has bad sharegpt turns.
+ rows = [
+ {
+ "messages": [
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello"},
+ ],
+ "conversations": [
+ {"from": "human", "value": None},
+ {"from": "gpt", "value": "OK"},
+ ],
+ }
+ ] * 5
+ mock_ds = _MockDataset(rows, ["messages", "conversations"])
+
+ print(
+ f" Rows: {len(rows)} — messages=clean chatml, conversations=bad sharegpt (value=None)"
+ )
+ stats = scan_dataset(mock_ds, fmt = "sharegpt")
+ col = stats.get("column", "?")
+ bad = len(stats.get("bad_row_indices", []))
+ # fmt='sharegpt' should scan 'conversations', find 5 bad rows.
+ correct_col = col == "conversations"
+ correct_bad = bad == 5
+ status = "PASS" if (correct_col and correct_bad) else "FAIL"
+ print(
+ f" [{status}] Explicit-fmt P2 fix: col={col!r} bad_rows={bad} "
+ f"(expected col='conversations' bad=5)"
+ )
+ print_report(stats, "sharegpt")
+ return stats
+
+
+def test_p2_gptoss_col_priority():
+ """P2 fix: fmt='gptoss' must scan 'messages' only, not fall through to
+ a clean 'conversations' column when messages is corrupt."""
+ section("P2 Fix Verification — fmt='gptoss' scans messages only, not conversations")
+
+ # messages is all-None (corrupt); conversations is clean sharegpt.
+ rows = [
+ {
+ "messages": None,
+ "conversations": [
+ {"from": "human", "value": "Hello"},
+ {"from": "gpt", "value": "Hi!"},
+ ],
+ }
+ ] * 5
+ mock_ds = _MockDataset(rows, ["messages", "conversations"])
+
+ print(
+ f" Rows: {len(rows)} — messages=None (corrupt), conversations=clean sharegpt"
+ )
+ try:
+ stats = scan_dataset(mock_ds, fmt = "gptoss")
+ col = stats.get("column", "?")
+ bad = len(stats.get("bad_row_indices", []))
+ correct_col = col == "messages"
+ correct_bad = bad == 5
+ status = "PASS" if (correct_col and correct_bad) else "FAIL"
+ print(
+ f" [{status}] gptoss P2 fix: col={col!r} bad_rows={bad} "
+ f"(expected col='messages' bad=5)"
+ )
+ print_report(stats, "gptoss")
+ return stats
+ except ValueError as exc:
+ print(f" [FAIL] scan_dataset raised ValueError: {exc}")
+ return None
+
+
+def test_new_p1_explicit_sharegpt_both_all_corrupt():
+ """NEW P1 (commit eb7fea3b7e): when fmt='sharegpt' and both 'messages' and
+ 'conversations' are all-corrupt in the first 100 rows, scan_dataset must scan
+ 'conversations' (the sharegpt column), NOT 'messages' (the generic probe's
+ first candidate)."""
+ section(
+ "NEW P1 — explicit fmt='sharegpt' scans 'conversations' even when both columns all-corrupt"
+ )
+
+ # Both columns are all-corrupt: every row has None.
+ rows = [{"messages": None, "conversations": None}] * 5
+ mock_ds = _MockDataset(rows, ["messages", "conversations"])
+
+ print(f" Rows: {len(rows)} — messages=None, conversations=None (both all-corrupt)")
+ try:
+ stats = scan_dataset(mock_ds, fmt = "sharegpt")
+ col = stats.get("column", "?")
+ bad = len(stats.get("bad_row_indices", []))
+ # MUST scan 'conversations', not 'messages'.
+ correct_col = col == "conversations"
+ correct_bad = bad == 5
+ status = "PASS" if (correct_col and correct_bad) else "FAIL"
+ print(
+ f" [{status}] New-P1 explicit sharegpt: col={col!r} bad_rows={bad} "
+ f"(expected col='conversations' bad=5)"
+ )
+ print_report(stats, "sharegpt")
+ return stats
+ except ValueError as exc:
+ print(f" [FAIL] scan_dataset raised ValueError: {exc}")
+ return None
+
+
+def test_new_p2_plain_string_messages_not_chatml():
+ """NEW P2 (commit eb7fea3b7e): a dataset where 'messages' contains plain
+ strings (not lists) must NOT be auto-classified as chatml. The all_corrupt
+ path in FORMAT_REGISTRY chatml match previously triggered here too."""
+ section("NEW P2 — plain-string 'messages' column must NOT be classified as chatml")
+
+ # messages is a plain text column, not a conversation column at all.
+ rows = [{"messages": "hello world"}] * 5
+ mock_ds = _MockDataset(rows, ["messages"])
+
+ print(
+ f" Rows: {len(rows)} — messages='hello world' (plain strings, not conversation)"
+ )
+ try:
+ stats = scan_dataset(mock_ds, fmt = "auto")
+ fmt = stats.get("format", "?")
+ # Classifying as chatml is wrong; 'unknown' or another non-chatml result expected.
+ not_chatml = fmt != "chatml"
+ status = "PASS" if not_chatml else "FAIL"
+ print(
+ f" [{status}] New-P2 plain-string messages: detected fmt={fmt!r} "
+ f"(expected: anything except 'chatml')"
+ )
+ return stats
+ except ValueError as exc:
+ # ValueError is also acceptable — the column isn't a valid conversation format.
+ print(
+ f" [PASS] New-P2 plain-string messages: scan_dataset raised ValueError (not chatml): {exc}"
+ )
+ return {
+ "format": "unknown",
+ "total_rows": 5,
+ "bad_row_indices": [],
+ "findings": [],
+ }
+
+
+def test_synthetic():
+ section("1. Synthetic Datasets (generated in-memory)")
+
+ sys.path.insert(0, str(REPO_ROOT / "tests" / "utils"))
+ from generate_dataset_with_none import (
+ make_alpaca_dataset,
+ make_chatml_dataset,
+ make_sharegpt_dataset,
+ )
+
+ results = {}
+
+ # ChatML — 10 clean rows (0-9), 8 bad rows (10-17)
+ ds_chatml = make_chatml_dataset()
+ stats = run_scan(ds_chatml, "Synthetic ChatML (messages/role/content)")
+ assert_bad_rows(stats, 8, "ChatML bad rows")
+ assert_exact_recall(stats, set(range(10, 18)), "ChatML exact recall")
+ results["chatml"] = stats
+
+ # ShareGPT — 5 clean rows (0-4), 5 bad rows (5-9)
+ ds_sgpt = make_sharegpt_dataset()
+ stats = run_scan(ds_sgpt, "Synthetic ShareGPT (conversations/from/value)")
+ assert_bad_rows(stats, 3, "ShareGPT bad rows")
+ assert_exact_recall(stats, set(range(5, 10)), "ShareGPT exact recall")
+ results["sharegpt"] = stats
+
+ # Alpaca — 5 clean rows (0-4), 5 bad rows (5-9)
+ ds_alpaca = make_alpaca_dataset()
+ stats = run_scan(ds_alpaca, "Synthetic Alpaca (instruction/output)")
+ assert_bad_rows(stats, 4, "Alpaca bad rows")
+ assert_exact_recall(stats, set(range(5, 10)), "Alpaca exact recall")
+ results["alpaca"] = stats
+
+ return results
+
+
+# ---------------------------------------------------------------------------
+# 2. HuggingFace: peteromallet/dataclaw-peteromallet
+# ---------------------------------------------------------------------------
+
+
+def _brute_force_bad_rows(ds, fmt: str) -> set:
+ """Pure-Python ground-truth scanner — zero shared code with dataset_none_detect.
+
+ Iterates every row and flags it bad if any field/turn contains None, empty,
+ or whitespace-only content. Returns the set of bad row indices.
+
+ Intentionally re-implements the same logic from scratch so that agreement
+ between this and scan_dataset() constitutes independent proof of correctness.
+ """
+
+ def _blank(val) -> bool:
+ if val is None:
+ return True
+ if isinstance(val, str) and val.strip() == "":
+ return True
+ return False
+
+ bad: set = set()
+ for i, row in enumerate(ds):
+ if fmt in ("chatml", "gptoss"):
+ msgs = row.get("messages")
+ if msgs is None or not isinstance(msgs, list):
+ bad.add(i)
+ continue
+ for turn in msgs:
+ if turn is None or (
+ isinstance(turn, dict) and _blank(turn.get("content"))
+ ):
+ bad.add(i)
+ break
+ elif fmt == "sharegpt":
+ convs = row.get("conversations")
+ if convs is None or not isinstance(convs, list):
+ bad.add(i)
+ continue
+ for turn in convs:
+ if turn is None or (
+ isinstance(turn, dict) and _blank(turn.get("value"))
+ ):
+ bad.add(i)
+ break
+ elif fmt == "alpaca":
+ if _blank(row.get("instruction")) or _blank(row.get("output")):
+ bad.add(i)
+ return bad
+
+
+def _assert_hf_no_misses(ds, stats: dict, label: str) -> bool:
+ """Independent ground-truth check: verify scan_dataset() found every bad row
+ that brute-force row-by-row iteration also finds.
+
+ brute_force_bad ⊆ module_bad → no misses (the key assertion)
+ module_bad ⊆ brute_force_bad → no false positives (informational)
+ """
+ fmt = stats.get("format", "unknown")
+ module_bad = set(stats.get("bad_row_indices", []))
+
+ print(f" Running brute-force independent scan (fmt={fmt!r}, {len(ds)} rows)...")
+ brute_bad = _brute_force_bad_rows(ds, fmt)
+
+ missed = brute_bad - module_bad # rows brute-force found but module missed
+ extra = module_bad - brute_bad # rows module flagged that brute-force didn't
+
+ no_misses = len(missed) == 0
+ snippet = ""
+ if missed:
+ sample = sorted(missed)[:10]
+ snippet = f" (first missed rows: {sample}{'...' if len(missed) > 10 else ''})"
+ status = "PASS" if no_misses else "FAIL"
+ print(
+ f" [{status}] {label} no-miss check — "
+ f"brute-force: {len(brute_bad)} bad rows | "
+ f"module: {len(module_bad)} bad rows | "
+ f"missed: {len(missed)}{snippet}"
+ )
+ if extra:
+ # Module may legitimately flag more rows than brute-force (e.g. extra
+ # structural checks) — informational only, not a failure.
+ print(
+ f" [INFO] {label} — module flagged {len(extra)} rows not in brute-force "
+ f"(may reflect additional structural checks, not false positives)"
+ )
+ return no_misses
+
+
+def test_dataclaw():
+ section("2. HuggingFace — peteromallet/dataclaw-peteromallet")
+ try:
+ from datasets import load_dataset
+
+ print(" Loading dataset (streaming first 500 rows for speed)...")
+ ds = load_dataset(
+ "peteromallet/dataclaw-peteromallet",
+ split = "train",
+ streaming = False,
+ )
+ print(f" Loaded {len(ds)} rows, columns: {ds.column_names}")
+ stats = run_scan(ds, "dataclaw-peteromallet")
+ if stats:
+ _assert_hf_no_misses(ds, stats, "dataclaw-peteromallet")
+ return stats
+ except Exception as exc:
+ print(f" [ERROR] Could not load dataclaw dataset: {exc}")
+ traceback.print_exc()
+ return None
+
+
+# ---------------------------------------------------------------------------
+# 3. HuggingFace: peteromallet/my-personal-codex-data
+# ---------------------------------------------------------------------------
+
+
+def test_codex_data():
+ section("3. HuggingFace — peteromallet/my-personal-codex-data")
+ try:
+ # load_dataset fails on this repo because ujson chokes on the large
+ # JSONL batch. Download the raw file and parse it ourselves instead.
+ from huggingface_hub import hf_hub_download
+ from datasets import Dataset
+
+ print(" Downloading conversations.jsonl via huggingface_hub...")
+ path = hf_hub_download(
+ "peteromallet/my-personal-codex-data",
+ "conversations.jsonl",
+ repo_type = "dataset",
+ )
+ rows = []
+ with open(path, encoding = "utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ rows.append(json.loads(line))
+ ds = Dataset.from_list(rows)
+ print(f" Loaded {len(ds)} rows, columns: {ds.column_names}")
+ stats = run_scan(ds, "my-personal-codex-data")
+ if stats:
+ _assert_hf_no_misses(ds, stats, "my-personal-codex-data")
+ return stats
+ except Exception as exc:
+ print(f" [ERROR] Could not load codex dataset: {exc}")
+ traceback.print_exc()
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Main
+# ---------------------------------------------------------------------------
+
+
+def main():
+ started = datetime.now().isoformat()
+
+ with open(LOG_PATH, "w", encoding = "utf-8") as log_file:
+ sys.stdout = Tee(log_file)
+
+ print(f"dataset_none_detect.py — Test Run")
+ print(f"Started: {started}")
+ print(f"Python: {sys.version}")
+ print(f"Log: {LOG_PATH}")
+
+ all_results = {}
+
+ all_results["p1_fix"] = test_p1_fix()
+ all_results["probe_p1_fix"] = test_probe_p1_fix()
+ all_results["probe_string_corrupt"] = test_probe_string_corrupt()
+ all_results["explicit_fmt_corrupt"] = test_explicit_fmt_corrupt()
+ all_results["p2_probe_valid_fallback"] = (
+ test_p2_probe_skips_corrupt_prefers_valid()
+ )
+ all_results["p2_explicit_col_priority"] = test_p2_explicit_fmt_col_priority()
+ all_results["p2_gptoss_col_priority"] = test_p2_gptoss_col_priority()
+ all_results["new_p1_sharegpt_all_corrupt"] = (
+ test_new_p1_explicit_sharegpt_both_all_corrupt()
+ )
+ all_results["new_p2_plain_string_not_chatml"] = (
+ test_new_p2_plain_string_messages_not_chatml()
+ )
+ all_results["synthetic"] = test_synthetic()
+ all_results["dataclaw"] = test_dataclaw()
+ all_results["codex_data"] = test_codex_data()
+
+ # ---------------------------------------------------------------------------
+ # Summary table
+ # ---------------------------------------------------------------------------
+ section("SUMMARY")
+ rows = [
+ ("Dataset", "Format", "Total rows", "Bad rows", "Bad turns"),
+ ]
+
+ def _row(label, stats):
+ if stats is None:
+ return (label, "ERROR", "-", "-", "-")
+ fmt = stats.get("format", "?")
+ total = stats.get("total_rows", "?")
+ bad = len(stats.get("bad_row_indices", []))
+ turns = stats.get("total_none_turns") or len(stats.get("findings", []))
+ return (label, fmt, str(total), str(bad), str(turns))
+
+ for key, label in [
+ ("chatml", "Synthetic chatml"),
+ ("sharegpt", "Synthetic sharegpt"),
+ ("alpaca", "Synthetic alpaca"),
+ ]:
+ s = all_results.get("synthetic") or {}
+ rows.append(_row(label, s.get(key) if isinstance(s, dict) else None))
+
+ rows.append(_row("dataclaw-peteromallet", all_results.get("dataclaw")))
+ rows.append(_row("my-personal-codex-data", all_results.get("codex_data")))
+
+ col_widths = [max(len(r[i]) for r in rows) for i in range(5)]
+ fmt_str = " " + " ".join(f"{{:<{w}}}" for w in col_widths)
+ header = rows[0]
+ print(fmt_str.format(*header))
+ print(" " + "-" * (sum(col_widths) + 10))
+ for row in rows[1:]:
+ print(fmt_str.format(*row))
+
+ # Write machine-readable JSON summary alongside the log
+ json_path = LOG_DIR / "none_detect_results.json"
+ summary = {}
+ for key, val in all_results.items():
+ if val is None:
+ summary[key] = None
+ elif isinstance(val, dict):
+ # Flatten synthetic sub-keys
+ if key == "synthetic":
+ for subkey, subval in val.items():
+ summary[f"synthetic_{subkey}"] = (
+ {
+ "format": subval.get("format"),
+ "total_rows": subval.get("total_rows"),
+ "bad_row_count": len(subval.get("bad_row_indices", [])),
+ "bad_turn_count": subval.get(
+ "total_none_turns", len(subval.get("findings", []))
+ ),
+ }
+ if subval
+ else None
+ )
+ else:
+ summary[key] = {
+ "format": val.get("format"),
+ "total_rows": val.get("total_rows"),
+ "bad_row_count": len(val.get("bad_row_indices", [])),
+ "bad_turn_count": val.get(
+ "total_none_turns", len(val.get("findings", []))
+ ),
+ }
+
+ json_path.write_text(json.dumps(summary, indent = 2), encoding = "utf-8")
+
+ finished = datetime.now().isoformat()
+ print(f"\nFinished: {finished}")
+ print(f"Log: {LOG_PATH}")
+ print(f"JSON: {json_path}")
+
+ sys.stdout = sys.stdout.stdout # restore
+
+
+if __name__ == "__main__":
+ main()