Skip to content

fix(validation): report the two inputs that end validate_file with a traceback - #669

Merged
christianeu-db merged 4 commits into
apache:mainfrom
kayemkim:validation/validate-file-crashes
Nov 1, 2026
Merged

christianeu-db merged 4 commits into
apache:mainfrom
kayemkim:validation/validate-file-crashes

Conversation

@kayemkim

@kayemkim kayemkim commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Two inputs end a validate.py run with a traceback instead of a diagnostic, and the files after them are not validated. Both came up while reviewing #595, which fixed the same two for a referenced mapping document but left the document itself as it was on main.

A scalar YAML cannot build. SafeLoader raises ValueError, AttributeError, KeyError or IndexError, not YAMLError, for 2024-02-30, !!int abc, !!timestamp abc, !!bool abc or !!int '', and validate_file caught only YAMLError and RecursionError. The loader now reports these as a YAML error at the node, so the message names the value, its tag and its line and reaches the branch both callers already have:

Error: Invalid YAML: cannot build 'abc' as timestamp
  in "bad.yaml", line 2, column 7:
    name: !!timestamp abc
          ^

The except clause #595 added on the mapping side goes away with it; a referenced document reports the same text after is not valid YAML.

Text stdout cannot encode. A "\ud800" escape loads as a lone surrogate, and the diagnostics that echo the text they are about, such as the duplicate field name and the SQL warning, carry it into print(), where the strict stdout encoder raises UnicodeEncodeError. A file name that is not valid UTF-8 decodes with a surrogate escape and fails the same way at Validation PASSED. The [Schema] messages were not affected because jsonschema reprs the value. main() now switches stdout to backslashreplace, so the text prints as \ud800 or m\udcff.yaml and the report completes.

Tests cover the five scalars, the surrogate and the file name, the first two alongside a second file that still has to pass. The new tests fail on main with the tracebacks; the file-name test skips where the file system refuses the name.

This does not overlap with #271, which adds a note after the schema errors; the two merge cleanly and the suite passes with both.

SafeLoader raises ValueError, AttributeError, KeyError or IndexError,
not YAMLError, for a scalar it cannot construct: 2024-02-30, !!int abc,
!!timestamp abc, !!bool abc, !!int ''. validate_file caught only
YAMLError and RecursionError, so a document holding one of these ended
the run with a traceback instead of a diagnostic, and the files after
it were not validated.

Catch them the way the mapping cross-checks already do for a referenced
document, and report the file as invalid YAML.
…rashing

A "\ud800" escape in a document loads as a lone surrogate, and the
diagnostics that echo the text they are about, such as the duplicate
field name and the SQL warning, carry it into print(). The strict stdout
encoder then raises UnicodeEncodeError after the check has already
found the problem, and the run ends with a traceback.

Switch stdout to backslashreplace at the start of main(), so the
surrogate prints as \ud800 and the report completes.

@christianeu-db christianeu-db left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for following up on the validate_file gap from #595. I checked out the branch, ran the suite , and confirmed that all six new tests fail on main with the tracebacks you describe. Two small points on the description: "It now catches the three" follows a list of four types (LookupError covers KeyError and IndexError, so it is correct, but it reads like a mistake). Also, the stdout change covers more than surrogates (see the inline comment). The main suggestion is inline on the diagnostic text and location.

Comment thread validation/validate.py Outdated
# Deeply nested input surfaces as RecursionError, not YAMLError.
print("Error: Invalid YAML: input is too deeply nested to parse")
return False
except (ValueError, AttributeError, LookupError) as e:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works, but three of the five cases print Python internals rather than something a model author can act on:

!!timestamp abc -> … cannot build: 'NoneType' object has no attribute 'groupdict'
!!bool abc -> … cannot build: 'abc'
!!int '' -> … cannot build: string index out of range
None of them gives a line number, but a YAMLError from the same file does. Also, the try covers all of load_yaml_named, so an AttributeError or IndexError from a bug in UniqueKeyLoader._check_unique_keys would be reported as bad input, with no type and no traceback.

The node is still in scope in construct_object, so one override could fix all three:

class _ValidatingLoader(UniqueKeyLoader):
    def construct_object(self, node, deep=False):
        try:
            return super().construct_object(node, deep)
        except (ValueError, AttributeError, LookupError) as e:
            tag = node.tag.rsplit(":", 1)[-1]
            raise ConstructorError(
                None, None, f"cannot build {node.value!r} as {tag}", node.start_mark
            ) from e

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took the override as written. The two except clauses around the loader go with it, including the one #595 added on the mapping side, so a referenced document reports the same text after is not valid YAML. The five scalars now print the value, the tag and the position:

Error: Invalid YAML: cannot build 'abc' as timestamp
  in "bad.yaml", line 2, column 7:
    name: !!timestamp abc
          ^

OssieDocument.from_ossie_yaml in the SDK loads with the plain UniqueKeyLoader and still lets these escape. I left the class here to keep this PR to validate.py; it could move to _loading.py if you want both covered.

Comment thread validation/tests/test_validate.py Outdated

assert code == 1
assert f"Error: Invalid YAML: {bad} holds a value YAML cannot build:" in output
assert "Traceback" not in output

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_run_cli returns only stdout, and traceback.print_exc() writes to stderr. An escaping exception already fails the test through pytest.raises(SystemExit). So this assertion passes in every case. Should it check capsys.readouterr().err, or should we remove it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed. As you say, an exception out of the load would already escape pytest.raises(SystemExit), and nothing on that path writes to stderr.

Comment thread validation/validate.py
# A diagnostic echoes the text it is about, and a "\ud800" escape in the document
# puts a lone surrogate in it that the strict stdout encoder refuses. Escape it
# instead of crashing after the check has already found the problem.
if hasattr(sys.stdout, "reconfigure"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes more than the surrogate case. On main, under en_US.UTF-8, a file name that is not valid UTF-8 (m\xff.yaml) also crashes at Validation PASSED: {yaml_path.name}. With this change it prints m\udcff.yaml. Could the comment and the description say that the change covers any text stdout cannot encode, file names included? A test for the file name would also help. One small side effect: under C.UTF-8, stdout is already surrogateescape and printed the original bytes; it now prints \udcff. I think that is fine.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reworded the comment and the description to say any text stdout cannot encode, file names included, and added the test. It writes os.fsdecode(b"m\xff.json") and skips where the file system refuses the name, which APFS does; on Linux it runs, and without the reconfigure line it fails with the UnicodeEncodeError at Validation PASSED.

The loader now turns the ValueError, AttributeError or LookupError that
SafeLoader raises for a scalar it cannot build into a ConstructorError at
the node, so the message names the value, its tag and its line instead of
a Python internal, and reaches the YAMLError branch both callers already
have. The two except clauses that caught the three exceptions around the
loader go away with it, and a bug in the loader outside a constructor is
no longer reported as bad input.
The stdout change covers any text the strict encoder refuses, not only a
lone surrogate from the document: a file name that is not valid UTF-8
decodes with a surrogate escape and crashed the report that names it. The
test skips where the file system refuses the name.
@kayemkim

kayemkim commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

Pushed two commits on top, one per point.

The validation workflow passes locally on current main, and the branch still merges cleanly with #271, #647 and #634 with their suites passing.

@christianeu-db christianeu-db left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kayemkim one small point below, which could be addressed in a followup PR

  • For an unquoted 2024-02-30, cannot build '2024-02-30' as timestamp no longer says "day is out of range for month", and a user who wanted a string may not see why a date was involved. Appending str(e) for a ValueError, or a "quote it to keep it as a string" hint, would help with that, which is probably the most common case. The value also has no length limit: a 5,000-digit !!int gives a 5,000-character line, while the snippet below it is already cut to about 75.

On the SDK: I agree it should be a separate PR in python/. Moving the class to _loading.py changes the exception type for from_ossie_yaml callers (from ValueError to YAMLError), so it deserves its own description.

@christianeu-db
christianeu-db merged commit dbdfb77 into apache:main Nov 1, 2026
12 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.

2 participants