Skip to content

format loaders: raise ParseError for input that cannot be loaded - #830

Open
Poseidonas wants to merge 6 commits into
cantools:masterfrom
Poseidonas:parse-error-everywhere
Open

Poseidonas wants to merge 6 commits into
cantools:masterfrom
Poseidonas:parse-error-everywhere

Conversation

@Poseidonas

Copy link
Copy Markdown
Contributor

Prerequisite for #827, split out as requested there.

The dbc, kcd, sym, arxml and cdd loaders now raise cantools.database.errors.ParseError whenever the input cannot be loaded, instead of a mix of ValueError, KeyError, textparser.ParseError and xml.etree.ElementTree.ParseError. Message text is unchanged, with two exceptions: num() in formats/utils.py had an unreachable fallback, so a bad number now gets its intended message rather than Python's float() one; and the three cdd KeyErrors lose the quotes str(KeyError) adds.

NotImplementedError for the unsupported ARXML direction in ecu_extract_loader.py is kept as is pending the question on #827; two converted sites in system_loader.py ("only AUTOSAR 3 and 4", "non-canonical references not yet supported") read as unsupported rather than malformed and can flip with it.

load_string() in database/__init__.py is not touched; #827 will be rebased on top of this.

@fallenmi fallenmi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The remaining unwrapped numeric conversions mean this does not yet establish the ParseError-only loader contract that #827 depends on.

On the current head (5002715), this syntactically valid KCD with an invalid input attribute still leaks a builtin exception:

from cantools.database.can.formats import kcd

text = '''<NetworkDefinition xmlns="http://kayak.2codeornot2code.org/1.0">
<Bus name="B"><Message id="0x1" name="M">
<Signal name="S" offset="0" length=""/>
</Message></Bus></NetworkDefinition>'''
kcd.load_string(text, strict=False)

The result is ValueError: invalid literal for int() with base 10: '', not cantools.database.errors.ParseError. The same path has other direct int() conversions for signal offsets, label values, mux counts, message IDs/intervals, lengths, and baud rates. A syntactically valid SYM that references an undefined signal can likewise still escape as KeyError during _load_message.

Today the broad probe in load_string() happens to catch these. Once #827 is rebased to catch only ParseError, they will escape rather than be retained in UnsupportedDatabaseFormatError. Please normalize the remaining input-derived failures (with regression coverage for a post-tokenization/attribute-conversion case), or narrow the promised contract before #827 relies on it.

AI assistance disclosure: OpenAI Codex was used to inspect the diff and run the adversarial reproducer; the technical finding and review submission were authorized by the account owner.

@Poseidonas

Copy link
Copy Markdown
Contributor Author

Confirmed — reproduced the KCD case on 5002715 (length="" escapes as a builtin ValueError from kcd.load_string). I'll add a boundary in each loader so failures after tokenisation also surface as ParseError, with the cases you list as regression tests, and push to this PR.

@Poseidonas

Copy link
Copy Markdown
Contributor Author

Done in 17ce3af. Every loader's load_string() is now wrapped at its boundary, so ValueError, KeyError, AttributeError, TypeError, IndexError and ArithmeticError raised after tokenisation are reported as ParseError chained from the original; the explicit checks keep their messages and a ParseError raised inside passes through unchanged. Regression tests cover the empty KCD length, a SYM message referencing an undefined signal, a non-integer DBC frame id and a string value for an INT attribute, a non-numeric ARXML BAUDRATE, a non-numeric CDD TEXTMAP bound and a CDD document without an ECU element — each via the loader and via load_string(..., database_format=...).

@fallenmi fallenmi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks — the original KCD and SYM post-tokenization cases are fixed on exact head 17ce3af, and the complete tests/test_database.py file passes here (201/201). One non-input boundary is still being converted by the new loader-wide decorator: sort_signals is a documented user callback, but its exceptions are now relabeled as parse failures.

Using tests/files/dbc/vehicle.dbc and a callback that raises a sentinel TypeError, direct dbc.load_string(text, sort_signals=callback) raises a new ParseError whose cause is the sentinel on this head. On previous head 5002715, the identical call raises the original sentinel object unchanged. I reproduced the same regression for callback-raised AttributeError, ValueError, and KeyError.

This means the narrowed probe planned in #827 would still classify unrelated user-code failures as unsupported database content, which is the same error-boundary problem #814 is trying to remove. Please limit conversion to input-derived loader failures (or otherwise let user callback failures escape unchanged) and add a sentinel callback regression alongside the new malformed-input matrix.

Follow-up review performed with OpenAI Codex assistance under the account owner authorization.

Comment thread src/cantools/database/utils.py Outdated
)


def raises_parse_error(func: Callable[_P, _T]) -> Callable[_P, _T]:

@andlaus andlaus Aug 27, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

instead of introducing this decorator which does basically the same as load_string() (what's the point?), I would like to see load_string() to be modified: if it catches a ParseError, no message is produced and the next format is tried, if it catches a NotImplementedError, it prints the error message belonging to the exception and refrains from probing further formats, and on any other exception it should print the error message belonging to the exception (plus adding that this is a buglet in cantools that ought to be fixed) and continue probing.

@andlaus andlaus Aug 27, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the task for this PR is then to ensure that no exceptions other than ParseError and NotImplementedError are raised by load_string() for the whole test suite.

@Poseidonas
Poseidonas force-pushed the parse-error-everywhere branch from 17ce3af to 93c5477 Compare August 27, 2026 07:51
@Poseidonas

Copy link
Copy Markdown
Contributor Author

Done as described: load_string() now swallows ParseError and tries the next format, re-raises NotImplementedError immediately, and for anything else logs the exception's message with a note that it is a bug in cantools and keeps probing; the decorator is gone. To make the second part hold, the test suite runs with a guard that fails any test in which a loader raises something other than a cantools Error/NotImplementedError, and every file under tests/files is loaded as every format under it. The corpus itself was already clean, but mutating single values in valid files turned up the sites in the last commit (KCD/SYM/DBC/CDD/ECU-extract int()/float() on input, SYM undefined signal references, DBC undefined attributes and out-of-range enum indices, ARXML number parsing, a zero denominator and an assert on scale limits); all now raise ParseError naming the offending value. Once this lands, #827 is redundant.

@Poseidonas

Copy link
Copy Markdown
Contributor Author

On the callback point: under the scheme andlaus asked for, an exception raised by a user callback such as sort_signals is not a statement about the input, so load_string() keeps its message, appends the "this is a bug in cantools" note, and continues probing the other formats (see test_load_string_sort_signals_exception).

@Poseidonas
Poseidonas force-pushed the parse-error-everywhere branch from 93c5477 to d817ac1 Compare August 27, 2026 08:05
@andlaus

andlaus commented Oct 22, 2026

Copy link
Copy Markdown
Member

with #827 merged, I feel more confident about this. Since the PR has been opened, there has been a pretty extensive cleanup of the DBC-related code so it needs to be rebased on the latest master branch.

@Poseidonas
Poseidonas force-pushed the parse-error-everywhere branch from d817ac1 to 80276a4 Compare October 22, 2026 09:07
@Poseidonas

Copy link
Copy Markdown
Contributor Author

Rebased on master. Three things it needed, the first one worth noting:

The cleanup added two checks for leftover VAL_ and SIG_VALTYPE_ entries that raise ValueError, and the guard in the last commit failed on them straight away. They now raise ParseError like the rest of the loader. That is the case this PR is for, so it is a good sign it caught them before I looked.

num and parse_int moved with the loader into the package, so the import is ..utils now. And load_string() keeps the probe warning that came with #827 rather than logging, since that is what is on master; the three tests for the probe outcomes assert on the warning instead of the log. The message in UnsupportedDatabaseFormatError is unchanged — a bug still reads DBC: "RuntimeError: boom" (this is a bug in cantools that ought to be fixed).

449 tests pass, ruff and mypy clean. Since _FORMAT_PROBE_ERRORS is gone with except Error in its place, the ValueError and KeyError I had to put in it for #827 are no longer needed, which was the part of that PR I was least happy with.

@Poseidonas
Poseidonas force-pushed the parse-error-everywhere branch from 80276a4 to 70366aa Compare November 4, 2026 10:31
@Poseidonas

Copy link
Copy Markdown
Contributor Author

Rebased on current master. Two things needed adapting, and one of them is worth a look before you spend time on the rest.

The commit that adapted to the VAL_/SIG_VALTYPE_ checks is gone, since #873 reverted them. I did not bring them back.

test_parse_failure_leaves_database_unchanged in tests/test_database_merge.py now fails, because it pins the exception types this PR is about:

db.add_<fmt>_string('invalid input')

          master                            this branch
dbc       textparser.ParseError             cantools ParseError
kcd       xml.etree.ElementTree.ParseError  cantools ParseError
sym       cantools ParseError               unchanged
arxml     xml.etree.ElementTree.ParseError  cantools ParseError

I updated it to expect ParseError for all four. That is a deliberate change to what callers see from add_*_string, so say the word if you would rather keep the third-party types exposed there.

Given #872, the thing you probably want to know is whether this rejects anything that used to load. Loading every file under tests/files as every format it is named for, at strict=True and strict=False, 278 attempts over 139 files:

master:  249 loaded, 29 failed
branch:  249 loaded, 29 failed

files that load on master and fail here:   0
files that load differently:               0
failures whose exception type changed:     0

load_file and load_string are untouched in this respect: both still raise UnsupportedDatabaseFormatError, so the wrapper hides the change from the probing path entirely. It is only visible where a single loader is called directly.

tox -e gh: 539 passed. tox -e ruff: clean. tox -e mypy: no issues on 3.10 through 3.14.

@Poseidonas Poseidonas moved this to Waiting on review in Industrial open source Nov 4, 2026
andlaus referenced this pull request Nov 17, 2026
Replace the export-only option with a database-owned comment, preserve scoped comments, and invalidate legacy cached database objects.
@andlaus

andlaus commented Nov 17, 2026

Copy link
Copy Markdown
Member

@Poseidonas: this one now has conflicts which need to be resolved.

@Poseidonas
Poseidonas force-pushed the parse-error-everywhere branch from 70366aa to 0e671ed Compare November 19, 2026 15:16
@Poseidonas

Copy link
Copy Markdown
Contributor Author

Rebased on current master. The one real conflict was in sym.py: #879 moved the message length into _load_message_length, which reads Len twice for a multiplexed message, so both reads now use parse_int. There is a test for a bad Len in a continuation section.

Testing #887 turned up two more cases that escaped as builtin exceptions, so I added them here:

  • a FLOAT attribute value "sNaN" raised ValueError;
  • an INT, FLOAT or HEX BA_DEF_ or BA_DEF_REL_ with a single bound raised IndexError.

Both now raise ParseError. Three or more bounds still load as on master, with the extra ones ignored.

All files in tests/files load the same as on master, in every format and in both strict modes. 616 passed on 3.10 and 3.14, ruff and mypy clean.

@Poseidonas
Poseidonas force-pushed the parse-error-everywhere branch from 0e671ed to 13421b2 Compare November 21, 2026 09:05
@Poseidonas

Copy link
Copy Markdown
Contributor Author

Rebased on master with #887. to_int/to_float keep its _decimal() and only turn the ValueError it raises, and the OverflowError from int() for Infinity, into ParseError. The four rejects_word tests pass unchanged and without the warning. Nothing else changed since the last push, and all files in tests/files still load the same as on master. 635 passed on 3.10 and 3.14.

If it makes the review easier, I can split this, for example the DBC changes from the other formats.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants