Skip to content

Accept instrument-level METADATA, as in mccode-antlr - #3180

Draft
g5t wants to merge 6 commits into
mainfrom
instr-metadata
Draft

g5t wants to merge 6 commits into
mainfrom
instr-metadata

Conversation

@g5t

@g5t g5t commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Free-form text area

Please describe what your PR is adding in terms of features or bugfixes:

Instrument-level METADATA, as in mccode-antlr. METADATA type name %{ ... %} worked for component definitions and instances. The grammar docs also listed it for instruments, but instrument.y rejected it there with a syntax error. mccode-antlr has always accepted it in the instrument header, so instruments written with it (e.g. the niess-generated ESS BIFROST model) could not be translated by mcstas.

ADR (proposed): docs/GRAMMAR/ADR-records/ADR_20261123_INSTRUMENT_METADATA.md

  • Grammar (instrument.y): zero or more METADATA blocks may follow SHELL and come before DEPENDENCY in the instrument header, the same place as in mccode-antlr. This is the only unambiguous position: after TRACE, a METADATA line could belong to the last component instance or to the instrument (2 shift/reduce conflicts).
  • Metadata table (metadata.c): instrument blocks are added after the component blocks. Each block has the instrument that defined it as its source, also when that instrument is %included, so inc:dup and my_instr:dup are separate entries. Only a block with the same source and name replaces another, e.g. a name repeated in one header. mccode-antlr needs the same change: it kept the source but replaced by name alone, so later includes silently removed earlier blocks. That is fixed in mccode-antlr#415, merged but not yet released.
  • Quoted names: METADATA text "notes" was stored as "notes", quotes included, so comp:notes never found it. It is now stored as notes. As in mccode-antlr, a name with spaces keeps its quotes (comp:"two words"), so it stays one entry in the space-separated --meta-defined output. The four metadatum alternatives collapse into one rule. No .comp or .instr in the repository uses a quoted name.
  • Runtime accessors (metadata-r.c). These bugs also hit existing component metadata:
    • --meta-list aborted with double free for any instrument with metadata. Without the crash it would have printed only the last source.
    • The key :: segfaulted --meta-defined, --meta-type and --meta-data, and File(metadatakey="::") in INITIALIZE.
    • metadata_table_name returned a freed pointer when the key was not found. File.comp does not reach that path today.
  • pygen (pygen.c.in): instrument METADATA was mixed into the component-definition metadata, which the generated script never uses. It now gets instance == 2 and is written as instr.add_METADATA(...), guarded by hasattr. McStasScript 0.0.97 has no instrument METADATA yet, so the script warns on stderr and continues. METADATA text is now a raw string (r"""..."""), so \" and \n in JSON survive; before, a JSON block with escapes no longer parsed. Text containing """ is still not escaped, as for the other code blocks with '''. McStasScript needs a separate PR for an instrument add_METADATA.
  • Unit test: new Test_lib_metadata in examples/libtest/ (McStas and McXtrace) checks the metadata-r accessors with instrument and instance METADATA: lookup by source and by source:name, quoted names with and without spaces, --meta-list (metadata_table_print_all_components), a missing key, and ::. It exits in INITIALIZE if a check fails; %Test: Ncount=10 Detector: PSD_I=10.
  • Regression test: test_File.instr (McStas and McXtrace) has a header METADATA block, which a third File writes to third.json. File stops with an error if the key is missing.
  • Docs: the instrument skeleton and §12 of INSTRUMENT_Grammar.md now show where instrument METADATA goes. INSTRUMENT_Grammar.html is not regenerated.

Behaviour change: a quoted metadata name without spaces used to be looked up with its quotes (comp:"notes"). It is now looked up without them (comp:notes). Names with spaces are unchanged.

Example:

DEFINE INSTRUMENT my_instr(a=1)
METADATA "application/json" config %{
{"x": 1}
%}
DEPENDENCY "..."
...
$ ./my_instr.out --meta-data my_instr:config
{"x": 1}
$ ./my_instr.out --meta-list
origin last my_instr

Tests:

  • bison reports no conflicts.
  • For all 375 McStas example instruments, the generated C is byte-identical to main apart from the date. pygen output differs only by import sys and the r prefix on METADATA strings.
  • A test instrument with instrument, instance, quoted-name and nested %included metadata (repeated names at each level) gives the same metadata table as mccode-antlr with #415. The --meta-* options, including the :: key, show no AddressSanitizer or UBSan errors.
  • test_File runs for McStas and McXtrace (under AddressSanitizer and UBSan), and with mccode-antlr, writing the instrument block to third.json.
  • A pygen script for an instrument with JSON METADATA was run against a stub McStasScript. With and without an instrument add_METADATA, the JSON values round-trip exactly; on main the instance JSON fails to parse.
  • Test_lib_metadata passes for McStas and McXtrace (PSD_I=10, under AddressSanitizer and UBSan). With the 3.10.2 runtime it fails at the missing-key check and then aborts in the --meta-list code.

Declaration of use of AI-tools

  • Please add a checkmark here if you used AI-tools during the work for this contribution

  • Further, please describe how / where and for what the tools were used:
    Claude Code (Claude Opus 5.5) was used throughout, directed and reviewed by me:

    • comparing instrument.y with the mccode-antlr grammar, and finding the conflict-free position for instrument METADATA;
    • drafting the changes to instrument.y, metadata.c, metadata-r.c, pygen.c.in and test_File.instr, the ADR and the grammar doc;
    • building McStas and McXtrace from source, and the tests listed above (example comparisons, sanitizer runs, mccode-antlr comparison, stub McStasScript run);
    • reading the review comments and the matching mccode-antlr change.

    The design decisions were mine: header placement, keying by (source, name), and keeping mccode-antlr's quoted-name rule.

  • AI-assisted commits must carry a Co-Authored-By line naming the tool, see CONTRIBUTING.md
    The commits after the first carry Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>. The first commit (3300a5f) was pushed without it, and I did not rewrite the pushed history to add it.


Development OS / boundary conditions

Please describe what OS you developed and tested your additions on, and if any special dependencies are required:

Linux x86_64 (devcontainer), conda-forge gcc 15.3.0, bison 3.8.2, flex 2.6.4, CMake 4.5.1. The McXtrace build used conda-forge gfortran 16.2.0. mccode-antlr was used from its main (v0.37.0+) with the #415 change. No new dependencies.

Not tested: macOS, Windows/MSVC, a real McStasScript make(), and McXtrace's pygen. willend built and checked McStas and McXtrace on macOS at 3300a5f (see the review comment).


PR Checklist for contributing to McStas/McXtrace

For a coherent and useful contribution to McStas/McXtrace, please fill in relevant parts of the checklist:

  • My contribution includes patches to an existing instrument file

    • I have used the mcdoc utility and rendered a reasonable documentation page for the instrument (please attach as screenshot in comments!)
    • I have used the mctest utility to test the instrument (please attach mcviewtest report as screenshot in comments)
    • I have used the mcrun --c-lint "linter" and followed advice to remove most / all warnings that are raised
  • My work touches the code-generator in mccode/src

    • I have added reasoning and documentation for the change through an ADR record in our GRAMMAR section
    • I am attaching test output in the comments
  • My work touches / adds to the runtime lib code (.c,.h etc in multiple locations

    • I have added reasoning and documentation for the change below
    • I am attaching test output in the comments
    • Unit test: every new or changed common/lib/share, mccode/nlib/share, mcstas-comps/share or mcxtrace-comps/share library and runtime file (.c, .h, .h.in) has a Test_lib_<name> instrument in examples/libtest/ (McStas and/or McXtrace), with a %Test: line where the result can be checked. If it cannot be standalone, say why in the free-form text (e.g. needs a component or external package)
  • My PR is meant to fix a specific, existing issue

    • I have indicated the issue number here:
    • I have added documentation for the fix and possible side effects

METADATA blocks may now follow SHELL in the instrument header. They are
added to the metadata table with the instrument name as source.

A quoted metadata name is stored without its quotes, so it is found by
the same key as an identifier name.

Fix --meta-list (double free, printed only the last source) and the crash
on keys without a source part, e.g. "::".

ADR: docs/GRAMMAR/ADR-records/ADR_20261123_INSTRUMENT_METADATA.md
@g5t

g5t commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

This grammar change implements the part of METADATA which I either forgot or found too-challenging in bison when I added the component-level feature. The segfaults were noticed previously but left unfixed since 'they anyway happened when the execution should halt' (from the command line interface) which became an incorrect assumption when File.comp was added.

I finally have a real use for it, so this proposed grammar change actually implements the rule (and regularizes keyname behavior with mccode-antlr)

The PR is ready except for a decision on the ADR -- do we have a procedure for accepting proposed ADRs?

@willend

willend commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Thanks @g5t, useful change and nicely small: the merged metadatum rule is much better.

On the ADR: there is no formal procedure. The ADR README only asks to keep the status updated and to link the PR. Earlier ones say e.g. "Accepted, with #2895". I am fine with accepting this one, so please set that status with this PR number once the points below are settled. I would not call it ready except for the ADR, though: points 1 and 2 need a change first.

Tested (macOS, main vs. this PR at 3300a5f)

  • McStas and McXtrace both build, bison reports no conflicts, and a test instrument with instrument, instance, quoted-name and %included metadata is accepted by both.
  • Generated C for the 375 McStas examples: no differences apart from dates, output paths and the embedded metadata-r.c.
  • You are right that File.comp makes the crashes matter: File(metadatakey="::") segfaults in INITIALIZE on main, and stops with "No unique metadata defined" here. --meta-list (abort) and --meta-type :: (segfault) are fixed too.
  • File writes instrument metadata correctly, both with my_instr:config and with the instrument name alone.
  • Quoted names are stored without quotes, as in mccode-antlr 0.36.0.
  • Not tested: Linux, Windows, running McXtrace, ASan/UBSan (sanitizer run hung, not investigated).

Please fix

1. %included metadata does not match mccode-antlr. The name handling now agrees, but this does not. With incA and then incB each defining dup, compared with mccode-antlr 0.36.0:

winner source
this PR incA my_instr
mccode-antlr incB incB
  • Order: collecting the blocks when the header is parsed fixes it and replaces the prepend and its comment. I built this: no conflicts, and incB wins.

    instr_metadata: metadata
    {
      if (!instrument_metadata) instrument_metadata = $1;
      else list_cat(instrument_metadata, $1);
    }
    ;

    The instrument rule then uses instr_metadata instead of metadata.

  • Source: you know best which is intended. I am fine with the master name here, but then please drop "as in mccode-antlr" from that sentence in the PR text and ADR, and "give the same metadata table" from the ADR (or change mccode-antlr to match).

2. mcstas-pygen loses instrument METADATA. The blocks have instance == 0, so they end up in component_definition_metadata, which the generated script never uses. Please give them their own instance value and write them out from instr->metadata (already de-duplicated).

McStasScript has no instrument-level METADATA yet (0.0.97), so an unguarded call would stop make() with an AttributeError. Suggestion:

if hasattr(instr, 'add_METADATA'):
    instr.add_METADATA(name='config', type='application/json', value=...)
else:
    print("Warning: this McStasScript drops instrument METADATA 'config'", file=sys.stderr)

(The generated script needs import sys.) McStasScript then needs a separate PR: an instrument add_METADATA, writing the blocks before DEPENDENCY. The method name is my assumption, we should agree with @mads-bertelsen about naming.

3. pygen does not escape the block text (existing problem, but JSON instrument blocks will hit it). The text goes unescaped into """...""", so {"x": "say \"hi\"\n"} becomes invalid JSON in Python, and """ in the text would break the script.

Minor

  • :name does not segfault on main for --meta-type, --meta-defined or --meta-data: it exits 1 cleanly. Only :: crashed for me, so please correct the PR text and ADR.
  • While you are in the accessors: metadata_table_name returns a freed pointer when the key is not found (if (!found) free(name); without name = NULL). File.comp does not reach it today.
  • A regression test would be good. A header block in the existing test_File.instr (McStas and McXtrace) is enough.
  • Please fill in the PR template, including the AI declaration.

@mads-bertelsen

Copy link
Copy Markdown
Contributor

Quick comment here, have not checked everything yet.

It will probably be simple enough to add on the McStasScript side. Should instruments support several metadata entries as well?

Was there a good reason not to use the PR template here? It forces us to record a lot of useful information and checks.

g5t and others added 5 commits November 23, 2026 20:18
Each instrument's METADATA keeps that instrument as its source, also when
it is %include-d, and only a block with the same source and name replaces
another. Before, included blocks were filed under the master instrument
and a repeated name kept whichever was parsed first, so the order of
%includes decided which one survived.

A quoted metadata name with spaces keeps its quotes, as in mccode-antlr,
so it stays one entry in the space-separated --meta-defined output.

ADR: correct the crashing keys (only "::" crashed, not ":name") and note
the matching mccode-antlr change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Instrument METADATA was mixed into the component-definition metadata,
which the generated script does not use. Mark it with instance 2 and write
it with instr.add_METADATA, guarded by hasattr since McStasScript has no
instrument METADATA yet; without it the script warns and continues.

METADATA text was written as a plain triple-quoted string, so Python
turned escapes like \" and \n into other characters and JSON blocks stopped
parsing. Write a raw string instead, as for the other code blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_File (McStas and McXtrace) gets a header METADATA block, written to
third.json by a third File instance, so the instrument-level path is
exercised whenever the example runs.

metadata_table_name freed the name it was given when the key was not
found, and returned it anyway. Return NULL instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Checks metadata-r with instrument and instance METADATA: lookup by source
and by source:name, quoted names with and without spaces, the --meta-list
listing, a missing key and the key "::". It exits in INITIALIZE if a check
fails. McStas and McXtrace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Link the matching mccode-antlr change, mccode-antlr#415.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@g5t

g5t commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Was there a good reason not to use the PR template here?

No, not a good reason -- gh pr create --body-file overrides the template, and the file I used for the original body was not based on the template.

@g5t

g5t commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @willend and @mads-bertelsen. All points are addressed in the commits after 3300a5f, and the description now follows the template, including the AI declaration.

1. %included metadata. mccode-antlr was wrong too: it replaced instrument blocks by name alone, although the table is looked up by source:name, so included instruments silently removed earlier blocks. Both translators now key instrument METADATA by (defining instrument, name), so the order of %includes no longer matters: ba64a0c here, and mccode-dev/mccode-antlr#415 (merged, not yet released). For quoted names, both now follow mccode-antlr: quotes are stripped, except for a name with spaces.

2. pygen drops instrument METADATA. Fixed in de4a54d. Instrument blocks get instance == 2 and are written as instr.add_METADATA(...), guarded by hasattr, with a warning on stderr otherwise. @mads-bertelsen: yes, an instrument can have several blocks, so it should take repeated calls.

3. pygen escaping. Also in de4a54d. METADATA text is now a raw string, r"""...""", like the other code blocks, so your JSON example survives. Text containing """ still breaks it, as ''' does for the other blocks; this is noted in pygen.c.in.

Minor

  • Only :: crashed, not :name: the description and ADR are corrected.

  • metadata_table_name now returns NULL for a missing key (3ce360a).

  • Tests:

    • test_File.instr has a header METADATA block.
    • New Test_lib_metadata (a4f85ae) covers the accessors.

    Both are for McStas and McXtrace, and pass on Linux under ASan/UBSan.

ADR set to "Accepted, with #3180" (f9a647f).

Not tested: macOS, Windows, a real McStasScript make().

@willend

willend commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Thanks @g5t, all points are resolved, and I am happy to approve this once it is out of draft.

Rechecked at f9a647f (macOS)

  • McStas and McXtrace build, and bison reports no conflicts.
  • %include: incA:dup, incB:dup and my_instr:dup are all kept and found. Keying by (source, name) is a better solution than my suggestion.
  • Test_lib_metadata (PSD_I=10) and test_File (third.json) pass for both flavours.
  • pygen with a real McStasScript 0.0.97: make() prints the warning and continues, and the instrument is written. With a stub add_METADATA, the blocks arrive. JSON with \" and \n survives.
  • Generated C for 372 McStas examples differs from main only in the embedded metadata-r.c (plus dates and paths), and the pygen output only by import sys. Two more examples (Test_Dispersion_relation_TAS, ESS_butterfly_MCPL_test) generate nothing in my setup, also on main.
  • CI is green.
  • Not tested: ASan/UBSan, running McXtrace's pygen output (it compiles), and the table comparison with mccode-antlr#415.

Notes, not blocking

  1. Same block name in several instruments: pygen writes one instr.add_METADATA(name='dup', ...) per instrument, and the source is lost. @mads-bertelsen: the component method rejects duplicate names, so if the instrument method does the same, make() stops with a ValueError (seen with a stub). Best settled in the McStasScript PR.
  2. Names with spaces through pygen: "two words" ends up as "\"two words\"" in the .instr written by McStasScript, which mcstas rejects with a syntax error. I saw this with component METADATA. From the code, main does this for every quoted name, so this PR makes it rarer.
  3. mccode-antlr: the 0.36.0 release can not compile Test_lib_metadata (unescaped quotes in the table). CI uses git main, so it passes, but we need a mccode-antlr release with Key instrument METADATA by source and name; escape the C table fields mccode-antlr#415 before the next McCode release.

@mads-bertelsen

Copy link
Copy Markdown
Contributor

Was there a good reason not to use the PR template here?

No, not a good reason -- gh pr create --body-file overrides the template, and the file I used for the original body was not based on the template.

Thanks for clarifying, I wonder if we can make it easier to include the template when using gh, perhaps there is some repo setting to enforce it.

Would like to review this and at least sketch the McStasScript interface before merge, but teaching the next couple of days.

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

⌂ Proxy