Skip to content

Add support for parsing YAML - #7340

Open
NaN-git wants to merge 28 commits into
NixOS:masterfrom
NaN-git:yaml
Open

NaN-git wants to merge 28 commits into
NixOS:masterfrom
NaN-git:yaml

Conversation

@NaN-git

@NaN-git NaN-git commented Nov 23, 2022 •

Copy link
Copy Markdown
Contributor

Why builtins.fromYAML?

YAML is widely used amongst other package managers and deployment tools. If we want better compatibility to these ecosystems, the ability to parse yaml efficiently in nix is useful, as it is for TOML and JSON, which we already support. Further discussion can be found, i.a., in #4910.

Description

YAML 1.2 is a complex standard and nix has a limited set of data types. Thus only a subset of YAML can be represented in nix. For example attribute sets require String keys, i.e. attribute sets can represent YAML maps with String keys only, and nix has no data types for binary data or dates. If builtins.fromYAML encounters YAML with incompatible data types, then it fails similar to builtins.fromTOML.

First, the implementation uses rapidyaml to parse the YAML string and afterwards the nix objects are created while traversing the YAML tree similar to builtins.fromTOML. Tags are mostly ignored and affect only scalars. Custom tags are always ignored and I don't see how custom tags could be handled by nix.

Why rapidyaml?

As part of nix robustness and safety of the implementation of builtins.fromYAML are important.

Some reasons why rapidyaml was chosen:

  • C++11 library with limited usage of dynamic memory allocations
  • tested with a wide range of compilers and on different platforms
  • extensive set of unit tests
  • heavy usage of assertions within the library
  • available as single header file, i.e. easy to bootstrap, so that no build tool could link another version of rapidyaml
  • good speed in comparison to yaml-cpp and other YAML libraries

limitations of rapidyaml

rapidyaml has a few limitations. Most of these limitations are not really relevant for the nix use case because of the limitations of nix.

Some comments with respect to the limitations:

  • The macro RYML_WITH_TAB_TOKENS is defined for builtins.fromYAML.
  • Anchor names terminated with a colon are not fully supported by rapidyaml. { &anchor: key: val, anchor: *anchor: } is parsed correctly, but this test case fails. The test case is ignored in the builtins.fromYAML-tests because it is an edge case and it's no valid YAML 1.3.
  • Otherwise the only issue that I found is that a string/block containing only tab-, space- and new line-characters might be parsed incorrectly as empty string (test case). I don't think that this limits the real world usage. UPDATE: This is fixed in the newest rapidyaml release.
  • ADDED: Rapidyaml has some issues parsing flow mappings entries with missing :-token and missing value, e.g. this example cannot be parsed.

Also rapidyaml parses some invalid YAML successfully, but that is actually helpful.
Otherwise the valid JSON {"a":"b"}, which is emitted by builtins.toJSON, could not be parsed by builtins.fromYAML because it is no valid YAML due to the missing separation white space after the :-token. UPDATE: Actually this is allowed in flow mappings.

Tested platforms

  • x86_64-linux
  • aarch64-linux

@DavHau

DavHau commented Nov 24, 2022

Copy link
Copy Markdown
Member

Like mentioned in #4910 (comment), we might want to consider to encode the yaml version into the function somehow. Instead of fromYAML it could be named fromYAML1_2. In case the YAML spec ever gets updated in an incompatible way, we could make a second function, like for example fromYAML2_0 and won't have to update/break the existing builtin.

@NaN-git

NaN-git commented Nov 24, 2022

Copy link
Copy Markdown
Contributor Author

Like mentioned in #4910 (comment), we might want to consider to encode the yaml version into the function somehow. Instead of fromYAML it could be named fromYAML1_2. In case the YAML spec ever gets updated in an incompatible way, we could make a second function, like for example fromYAML2_0 and won't have to update/break the existing builtin.

If this should be implemented, then a decision about the versioning scheme is needed and how the versioning should be done, i.e. whether the builtins should have different names or whether a function with additional version argument should be used instead. Having explicitly different function names would be advantageous with respect to reproducibility.

The versioning should apply to different code versions, not only to different YAML standards, so that bug compatibility can be retained. The YAML standard is ugly and we need to parse real world data, i.e. the "YAML" might be invalid, so that some tradeoffs are required...

I'm wondering how updates of builtins.fromJSON and builtins.fromTOML are handled. builtins.fromJSON uses nlohmann-json, but if nix isn't built by nix, then the linked library version isn't fixed. Did this cause any problems yet?

Comment thread src/libexpr/primops/fromYAML.cc Resolved
Comment thread src/libexpr/primops/fromYAML.cc Resolved
@nixos-discourse

Copy link
Copy Markdown

@fricklerhandwerk fricklerhandwerk added the feature Feature request or proposal label Dec 5, 2022
@nixos-discourse

Copy link
Copy Markdown

This pull request has been mentioned on NixOS Discourse. There might be relevant details there:

https://discourse.nixos.org/t/how-to-convert-yaml-nix-object/23755/2

@DavHau

DavHau commented Dec 21, 2022

Copy link
Copy Markdown
Member

Like mentioned in #4910 (comment), we might want to consider to encode the yaml version into the function somehow. Instead of fromYAML it could be named fromYAML1_2. In case the YAML spec ever gets updated in an incompatible way, we could make a second function, like for example fromYAML2_0 and won't have to update/break the existing builtin.

I discussed this once more with @NaN-git and it doesn't seem like a good idea to encode the yaml spec version in the function name. rapidyaml doesn't distinguish between yaml versions. It's hard to forsee the reason for which we would have to introduce a new fromYaml in the future, if ever.

Whatever naming schema we would come up right now, there is a high chance that it won't be meaningful. Therefore I think the builtin should just be introduced as a plain fromYaml. If it ever needs to be updated then we can still make a fromYaml_2 or whatever makes sense in that situation.

@nixos-discourse

Copy link
Copy Markdown

This pull request has been mentioned on NixOS Discourse. There might be relevant details there:

https://discourse.nixos.org/t/2023-01-02-nix-team-meeting-minutes-20/24403/1

@fricklerhandwerk

fricklerhandwerk commented Jan 10, 2023 •

Copy link
Copy Markdown
Contributor

Discussed in Nix team meeting on 2023-01-09:

  • general sentiment is in favor of merging this
  • don't vendor the dependency, do it like with nlohmann
  • we will wait for @edolstra's input for the final decision
Complete discussion
  • @roberth: vendoring the library is actually nice, because it doesn't change underneath
    • @thufschmitt: should follow the decision on the nlohmann JSON library
      • that was a special case though, because it was very uncommon yet easy to vendor
    • @roberth: the problem with vendoring is that it requires re-exporting the symbols such that names don't collide
      • John: in short, vendoring is only a good fit for private deps, and so so for a public dep one needs to do these things.
    • @thufschmitt: not vendoring makes packaging for third parties more painful. e.g. there is no rapidyaml on Debian
  • @roberth: in favor of the addition after being against it. In general adding more (external) code does not help with the guarantee for evaluation reproducibility 10 years down the line
  • @Ericson2314: see the practical reasons. it would be better for IFD to work efficiently so one can do the conversion independent of Nix proper, but I also don't see that happening in the near term.
    • @roberth: the main deficiency of IFD is system specificity
  • @thufschmitt: in favor of the feature. we should provide strong control of inputs to derivations. IFD breaks the separation between evaluation and build, and therefore breaks reproducibility guarantees (one can create any inputs at build time, which may be non-deterministic)
  • @fricklerhandwerk: generally agree with @Ericson2314, we should be really careful about growing the API surface. not against the feature though, because it's obviously useful and adds symmetry to the API. we should just make sure we know how to deal with such additions in the future, and have a clear stance to present to contributors.
  • agreement:
    • don't vendor the dependency, do it like with nlohmann
  • @tomberek: agree in principle, it's a natural parallel to the to/fromJSON builtins.
  • we will wait for @edolstra's input

@nixos-discourse

Copy link
Copy Markdown

This pull request has been mentioned on NixOS Discourse. There might be relevant details there:

https://discourse.nixos.org/t/2023-01-09-nix-team-meeting-minutes-22/24577/1

@domenkozar

Copy link
Copy Markdown
Member

@edolstra any reason not to merge this?

@tomberek

Copy link
Copy Markdown
Contributor

Decisions

  • agreement on not vendoring
  • agreement on making this an experimental feature

Issues to clarify

  • Nix's compile time impact?
  • closure size?
  • static link?
  • show various features and how they map to Nix values
    • add tests for the features
  • testing framework improvements
    • add explanation of testing
    • convert bash to google-test approach?

Versioning

If the underlying library returns different results over time, this impacts reproducibility

@NaN-git

NaN-git commented Jan 31, 2023

Copy link
Copy Markdown
Contributor Author

Issues to clarify

[...]
* [ ] show various features and how they map to Nix values

  * [ ]  add tests for the features

* [ ]  testing framework improvements
  
  * [ ]  add explanation of testing
  * [ ]  convert bash to google-test approach?

Regarding the tests:

  • The tests from yaml-test-suite are converted to gtest tests by a bash script. The resulting test suite is part of the PR.
  • The tests contain a JSON representation ("json") of the YAML ("yaml") test cases. Thus the tests check whether builtins.fromJSON json == builtins.fromYAML json == builtins.fromYAML yaml holds true by serializing the nix expressions. Several hundred test cases are executed and compatibility between builtins.fromJSON and builtins.fromYAML is verified at least for these cases. If yaml should be invalid then the test case is skipped because rapidyaml will often parse this without error.
  • builtins.fromYAML converts a YAML file to the following nix types: maps, lists, strings, integers (int64) and floats (double). Conversion to custom data types or interpreting data as nix expression would be very dangerous.
    Alias nodes (references) are automatically resolved, e.g.
builtins.fromYAML ''
---
values:
  - &value someValue
--- 
# some YAML template
template: *value
''

evaluates to (I'm not very happy with the handling of multiple documents)

[
  {
    values = [ "someValue" ];
  }
  {
    template = "someValue";
  }
]

Build questions

rapidyaml uses cmake as build system. I don't think that this a good choice for nix because bootstrapping of nix has to be easy. The only dependency of rapidyaml is c4core from the same author.
Thus it should be easy to statically link the library. At the moment the library is included as single header file similar to builtins.fromTOML.
What is the best way to include this library into nix?

Even with rapidyaml as single header file the build time of builtins.fromYAML seems to be faster than the build time of builtins.fromTOML and the size of the object file is much smaller than the size of the builtins.fromTOML object file.

@Ericson2314

Copy link
Copy Markdown
Member

What is the best way to include this library into nix?

I would package it and its dependency in Nixpkgs. I am happy to help with that part if you want.


I personally am not to concerned about the bootstrapping because we could always make YAML a (compile time of Nix) optional feature.

@NaN-git

NaN-git commented Feb 1, 2023

Copy link
Copy Markdown
Contributor Author

I would package it and its dependency in Nixpkgs. I am happy to help with that part if you want.

I personally am not to concerned about the bootstrapping because we could always make YAML a (compile time of Nix) optional feature.

Packaging rapidyaml is rather easy:

{ cmake
, fetchFromGitHub
, git
, stdenv
, enableStatic ? true
}:
stdenv.mkDerivation rec {
  pname = "rapidyaml";
  version = "0.5.0";

  src = fetchFromGitHub {
    owner = "biojppm";
    repo = pname;
    rev = "v${version}";
    fetchSubmodules = true;
    hash = "sha256-1/P6Szgng94UU8cPFAtOKMS+EmiwfW/IJl2UTolDU5s=";
  };

  nativeBuildInputs = [ cmake git ];
  cmakeFlags = [
    "-DRYML_WITH_TAB_TOKENS=ON"
    "-DBUILD_SHARED_LIBS=${if enableStatic then "OFF" else "ON"}"
  ];
}

I prefer to statically link this because the static library is rather small (~500 KB).

In my opinion not only bootstrapping of nix has to be easy, but compiling it for other distributions should be easy, too. I don't know how to add rapidyaml as optional dependency to nix, so that builds without nix aren't messed up.

@NaN-git

NaN-git commented Feb 11, 2023

Copy link
Copy Markdown
Contributor Author

I removed rapidyaml as single header file and made it an optional library instead. If the library cannot be found then builtins.fromYAML is not available. Rapidyaml is not part of nixpkgs yet, so that I added the package to flake.nix and it will be linked statically.
With builtins.fromYAML the size of libnixexpr increases by 800KB and in my tests on an AMD 5800U the build time of nix increased by 4-5 seconds to ~176 seconds when compiling with 16 threads.

Regarding the testing framework: I need more information what's actually required/wanted. I commented some point in #7340 (comment). Of course it would be possible to preprocess the tests differently so that less logic is needed in the testing code and it would be more obvious which tests are executed actually.

@fricklerhandwerk

fricklerhandwerk commented Feb 13, 2023 •

Copy link
Copy Markdown
Contributor

If the library cannot be found then builtins.fromYAML is not available.

@edolstra what do you think about an optional built-in? Doesn't sound right to me.

@roberth

roberth commented Feb 13, 2023

Copy link
Copy Markdown
Member

If the library cannot be found then builtins.fromYAML is not available.

@edolstra what do you think about an optional built-in? Doesn't sound right to me.

Supporting a build without yaml library might be useful for some build-from-source bootstrapping process, but in this case it must be an explicit choice to remove the yaml feature and create an incomplete Nix. It must not happen by accident.

@roberth

roberth commented Feb 13, 2023

Copy link
Copy Markdown
Member

Whether that's even a worthwhile effort, I don't know. Personally I think bootstrapping Nix from source is not an important use case, but packaging by other distros is. Those distros must not package a Nix without yaml though! I'd rather require rapidyaml unconditionally.

@NaN-git

NaN-git commented Feb 13, 2023

Copy link
Copy Markdown
Contributor Author

Whether that's even a worthwhile effort, I don't know. Personally I think bootstrapping Nix from source is not an important use case, but packaging by other distros is. Those distros must not package a Nix without yaml though! I'd rather require rapidyaml unconditionally.

Ok, I see two possible solutions:

  1. Always link against libryml, but then it won't be easy to compile it without rapidyaml. This would enable the removal of some lines of code.
  2. Require rapidyaml unless --disable-ryml is specified, i.e. a few lines of configure.ac have to be changed.

- add additional argument to fromYAML for optional parameters of the parser

- adhere to the YAML 1.2 core schema

- much stronger error checks and improved error messages

- proper conversion of null, floats, integers and booleans

- additional testcases and more checks for expected failures
- restrict patterns of floats and ints to patterns defined by YAML 1.2 core schema

- parse integers with tag !!float

- map: enforce key uniqueness
fix: parse "!!float -0" as -0.0
@NaN-git
NaN-git force-pushed the yaml branch 2 times, most recently from 610cd2f to ce61749 Compare January 9, 2025 12:25
@NaN-git
NaN-git requested a review from roberth January 9, 2025 20:23
@nakoo

nakoo commented May 6, 2025

Copy link
Copy Markdown

It seems the PR is ready, but it still hasn't been merged. Is there an underlying reason that hasn't been mentioned here?

@gabyx

gabyx commented May 13, 2025

Copy link
Copy Markdown
Member

@roberth Could you maybe give this another chance, loading yaml is so utterly needed :). Thanks a lot. Even if it becomes experimental feature, I am happy about it.

Comment thread src/libexpr-tests/yaml.cc
Value rymlJson = fromYAML(state, root, {});
EXPECT_EQ(printValue(state, refJson), printValue(state, rymlJson));
start = ss.tellg() + std::streampos(1);
}

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.

sugg: maybe a comment why this empty catch here

Comment thread src/libexpr-tests/yaml.cc
bindings.alloc("useBoolYAML1_1").mkBool(true);
options.mkAttrs(bindings);

Value val = parseYAML("[ true, True, TRUE, y, Y, on, On, ON, yes, Yes, YES ]", options);

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.

question: is this really yaml ( then I didnt know) or does Nix parse these as booleans?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sadly, YAML 1.1 specifies that this should be parsed as booleans, e.g. kubernetes relies on this behavior. By default Nix uses YAML 1.2, where this is parsed as strings.

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.

Ah ok! (but doo whyyy??? lol)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's a misconception that YAML would be simple. Instead the standard is very complex and making YAML 1.2 a superset of JSON didn't simplify it.

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.

Hmm. jeah thats why people probably want toml over yaml sometimes. I am happy when this gets merged, not sure whats taking so long, ok its a new dependency? I guess the ecosystem benefits from such a function a lot.

Does that yaml parser also support references?

{.name = "__fromYAML",
.args = {"e", "attrset"},
.doc = R"(
Convert a YAML 1.2 string *e* to a Nix value, if a conversion is possible.

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.

Nice doc!

@samos667

samos667 commented Aug 11, 2025 •

Copy link
Copy Markdown

I can't wait to test this new experimental features!

Do we know if the merge is planned, and if so, when?

@emilazy

emilazy commented Aug 14, 2025

Copy link
Copy Markdown
Member

The pain of things like #13741 and NixOS/nixpkgs#433710 would make me extremely hesitant to bake another complex and underspecified serialization format into the evaluation semantics of the language.

@NaN-git

NaN-git commented Sep 5, 2025 •

Copy link
Copy Markdown
Contributor Author

The pain of things like #13741 and NixOS/nixpkgs#433710 would make me extremely hesitant to bake another complex and underspecified serialization format into the evaluation semantics of the language.

I don't think that something like #13741 can happen here. Rapidyaml parses the YAML tree only. The application (nix) is responsible to chose the type of leaf nodes and to parse them.

The type of scalars is chosen according to the rather simple YAML core schema (keys are always parsed as strings because nix cannot handle anything else).

The number parsing has an external dependency, so that some risk remains, but neither the nix parser vendors number parsing.

No YAML serialization is done.

@emilazy

emilazy commented Sep 5, 2025

Copy link
Copy Markdown
Member

I looked at the changelog for the most recent version of Rapid YAML. It seems like the fix for biojppm/rapidyaml#484 would cause a breaking change in Nix evaluation semantics, right?

@NaN-git

NaN-git commented Sep 5, 2025

Copy link
Copy Markdown
Contributor Author

I looked at the changelog for the most recent version of Rapid YAML. It seems like the fix for biojppm/rapidyaml#484 would cause a breaking change in Nix evaluation semantics, right?

Yes, a bug in the library can affect nix and before this PR is merged I would update the minimum required version (still it would be an experimental feature).
A bug in nlohmann::json could affect nix, too, because no specific version is pinned, although nlohmann::json is mature and the complexity of the JSON standard is low.

Would your quoted bug affect builds?
Probably not assuming that this feature would be used to parse YAML lock files, which should (TM) require a smaller subset of the YAML standard.
The big elephant in the room is: Which YAML subset is actually required? I don't know.

The concerns have to be tackled before this feature can become non-experimental.

@gabyx

gabyx commented Sep 11, 2025

Copy link
Copy Markdown
Member

@NaN-git : Isnt it that we can trust this function to be deterministic to the future by locking the dependencies for nlohman and rapidyaml etc ? But maybe that is not enough: Cause I guess @emilazy probably points out that only a real subset should be enabled (no anchors etc ? no other arcane things?)
which makes any update of this yaml parsing in the future easier and bugfixes in rapidyaml (and deps) do not trickle down into the evaluation and making everything non-determ when nix is upgraded etc? Do I understand correctly?

@xokdvium

Copy link
Copy Markdown
Contributor

Isnt it that we can trust this function to be deterministic to the future by locking the dependencies for nlohman and rapidyaml etc

This would effectively constitute forking/vendoring those libraries and maintaining them ourselves for all eternity to be compatible with newer compilers e.t.c.

It's also doubtful that we'd want to bake problematic and buggy behaviour and declare that to be stable for all eternity.

The problem is that such underspecified and hard to implement stuff as YAML is too much of an API surface to effectively guarantee stability. Doing this would absolutely require adding comprehensive fuzzing and a gigantic corpus of tests to regular regression tests. This is something nix is totally lacking at the moment.

@gabyx

gabyx commented Sep 12, 2025 •

Copy link
Copy Markdown
Member

Aha: Then the only way forward is ditch this PR, which is really sad given the amount of work went in and implement a simple yaml parser in Nix which nobody wants to do, resulting in the same problem

@x10an14

x10an14 commented Sep 12, 2025

Copy link
Copy Markdown

Aha: Then the only way forward is ditch this PR, which is really sad given the amount of work went in and implement a simple yaml parser in Nix which nobody wants to do, resulting in the same problem

If so, you could always roll your own, like I did here: https://git.sr.ht/~x10an14/nix-conf-langs/tree/main/item/languages.nix#L32

@gabyx

gabyx commented Nov 9, 2025

Copy link
Copy Markdown
Member

@NaN-git Any chance this PR gets merged and experimental status?

@roberth

roberth commented Nov 9, 2025

Copy link
Copy Markdown
Member

I can't speak for the nix team, but:

Doing this would absolutely require adding comprehensive fuzzing and a gigantic corpus of tests to regular regression tests.

This could be done if there's sufficient interest in refining a YAML spec and (possibly) maintaining a fork of rapidyaml so that it continues to implement the extra detailed spec.
I wouldn't recommend that the team divides its attention this way, but the 👍 and ❤️ suggestions suggest to me that at least the maintenance part could be covered by the community. There may also be interest in this kind of thing outside the Nix/NixOS community. If someone's interested in doing the fuzzing, I believe that could make this happen.

@samos667

samos667 commented Nov 9, 2025 •

Copy link
Copy Markdown

Tbh I don't understand why this take so long to merge a experimental feature ? Could we consider to address previously mentioned issues in the PR that will make this feature "prod-ready"?

Just my honnest opinion, but I'll have lose my mind if I was @NaN-git. This PR was initiated three years ago.

Edit: Never mind. I thought the author was waiting for the team to merge.

@xokdvium

xokdvium commented Nov 9, 2025

Copy link
Copy Markdown
Contributor

FWIW, last this was discussed during a team meeting @Mic92 mentioned that even @NaN-git is unsure if this patch can be merged.

@Ericson2314

Copy link
Copy Markdown
Member

@samos667 I would also like to remind you that every line of code is a liability, and every new feature is a liability. Remember https://www.hyrumslaw.com/ . It might sound silly, but this is the reality of maintaining a widely use piece of software, trying to preserve simplicity, and maintain stability

@gabyx

gabyx commented Feb 7, 2026

Copy link
Copy Markdown
Member

Aha: Then the only way forward is ditch this PR, which is really sad given the amount of work went in and implement a simple yaml parser in Nix which nobody wants to do, resulting in the same problem

If so, you could always roll your own, like I did here: git.sr.ht/~x10an14/nix-conf-langs/tree/main/item/languages.nix#L32

I need deserialization.

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

feature Feature request or proposal language The Nix expression language; parser, interpreter, primops, evaluation, etc with-tests Issues related to testing. PRs with tests have some priority

Projects

Status: ⚖ To discuss

Development

Successfully merging this pull request may close these issues.