# Fix "Psych::BadAlias: Unknown alias" When Loading YAML on Ruby 3.1

Yes. An agent finds each YAML.load that reads aliased YAML, turns aliases back on without unsafe loading, tests it on old and new Rubies, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/fix-psych-badalias-unknown-alias/psych/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

Ruby 3.1 ships Psych 4, where `YAML.load` became the safe loader. It refuses classes it was not told about, and it refuses aliases unless asked. A YAML file that shares settings through an anchor, `defaults: &defaults`, and merges them with `<<: *defaults` no longer loads. On Ruby 3.1 the message is `Unknown alias: defaults (Psych::BadAlias)`. On Ruby 3.3, which has Psych 5, the same line raises `Psych::AliasesNotEnabled`, a subclass, and says "Alias parsing was not enabled. To enable it, pass `aliases: true` to `Psych::load` or `Psych::safe_load`." binarylogic/settingslogic is a clean example. Line 103 of `lib/settingslogic.rb` reads the settings file with `YAML.load(ERB.new(file_contents).result).to_hash`, and the sample `config/application.yml` in its README defines `&defaults` and merges it into `development`, `test` and `production`.

The agent starts from that README sample and not from the test suite, because the suite cannot see the problem: `spec/settings.yml` has no anchors. With a current rspec on Ruby 3.3, 26 of the 27 examples pass, and the one failure is the retired `be_false` matcher on line 87 of the spec file, which has nothing to do with YAML. So the agent copies the README's YAML into a new fixture and writes a spec that loads it with the `development` namespace, expecting `neat_setting` to be 800 and `cool.saweet` to be "nested settings". The spec fails with the alias error, which is the proof the fix has to overturn.

Three replacements exist and they are not equal. `YAML.unsafe_load` brings back everything the old `load` did, including building any Ruby object the file names. `YAML.load(yaml, aliases: true)` turns aliases on and still refuses unknown classes. `YAML.safe_load(yaml, aliases: true)` is stricter again. A settings file is trusted input, but the agent takes the narrowest option that keeps existing files loading, which is `aliases: true`. There is one catch. The gemspec sets no minimum Ruby and `.travis.yml` still lists Rubies from 1.8.7 to 2.1.2, and Psych 3.1 on Ruby 2.7 rejects the keyword with `ArgumentError: unknown keyword: :aliases`. So the call goes into a small private method that tries `aliases: true` and falls back to plain `YAML.load` on that `ArgumentError`.

Then it widens the search, since an application usually meets this error in its own code. It greps for every `YAML.load`, `YAML.load_file` and `Psych.load` and, for each, records which file is read and whether that file can contain anchors or Ruby objects. A call that parses anything from outside the repository, such as an upload or an HTTP response, is reported and left on the safe loader. When the failing call is inside a gem the application depends on, as it would be for an application that uses settingslogic, the agent looks for a release that contains the fix and bumps to it, or says none exists and proposes a patch upstream.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This project fails on Ruby 3.1 or later with \"Psych::BadAlias: Unknown alias\" (on newer Rubies, \"Psych::AliasesNotEnabled: Alias parsing was not enabled\") when it loads a YAML file that uses anchors and merge keys. Fix it. Find every call to YAML.load, YAML.load_file, Psych.load and Psych.load_file. For each, record which file or string it reads, whether that input is under the repository's control, and whether it can contain aliases, symbols or serialized Ruby objects. Reproduce the failure first with a spec that loads a YAML file containing an anchor and a merge key; if the project's README or sample configuration shows such a file, use that. Fix trusted configuration loads by passing aliases: true and keep the class restrictions; do not switch to unsafe_load unless a file really contains Ruby objects, and say which file if so. Never widen a call that parses input from outside the repository. Read the gemspec and CI configuration for the oldest Ruby the project supports, and if that Ruby's Psych does not accept the aliases keyword, keep the code working there too. Run the new spec and the existing suite on the oldest and newest Ruby you can install, and report results for each, listing failures that have another cause separately. If the failing call is inside a dependency, upgrade to a release that fixes it or report that none exists. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with a few changed lines in the loader, a new YAML fixture that uses an anchor and merge keys, and a spec that loads it. The description gives the result for each Ruby the agent installed: on the unchanged code the README sample loads on Ruby 2.7 and fails on 3.1 and 3.3 with the two messages above, and on the changed code it loads on all of them, 3.4 included, with the values the README promises.

The description keeps unrelated failures apart. In settingslogic that is the one `be_false` example, which fails before and after the change because the matcher's name changed in rspec 3. The agent lists it with its line number and leaves it, so the diff stays about YAML.

What a reviewer weighs is the loading mode, and the description states it in one sentence: aliases are enabled, object deserialization is not. It also lists each `YAML.load` call it left untouched and why. If one of your files does hold serialized Ruby objects, the agent names the file and the classes instead of reaching for `unsafe_load` across the board, and that decision stays with you.

## Run it on every error tracker alert

In production this arrives as an exception on boot or on the first request that reads configuration, right after a Ruby upgrade. Create an automation in the Project with a `webhook` trigger and this prompt. Most error trackers sign their own webhook deliveries and cannot send the `Authorization: Bearer` header a Rush `webhook` trigger requires, so put a small handler on your server between the two. It receives the tracker's alert, keeps the ones whose exception class is `Psych::BadAlias` or `Psych::AliasesNotEnabled`, and posts the stack trace to the trigger's URL with the trigger's secret.

The trace lands after the saved prompt as event text, and its first application frame tells the agent which `YAML.load` to begin with. Have the handler send an `Idempotency-Key` header on its call to the trigger's URL, built from the tracker's issue id, so a redelivered alert starts nothing new. Keep the automation's max runs per hour low: a process that cannot boot raises the same exception on every restart.

## Why run it on Rush?

The fix is a keyword argument, and the risk is in everything around it. It has to work on the Ruby you are leaving and the Ruby you are moving to, and those ship different Psych majors with different method signatures. In its own sandbox the agent installs several Rubies side by side and runs the same spec on each, something a laptop pinned to one version by `.ruby-version` rarely does. The output of each run is kept in the session, so the claim that it loads on 2.7 and on 3.3 is something a reviewer can read.

It is also a change with a security edge, and the session shows which way the agent leaned. A one-line `unsafe_load` would have made the error disappear too. The transcript has the grep for every load call, the reasoning for each, and the test output, so a reviewer who cares about deserialization can check the choice against the evidence instead of trusting a summary.

## Frequently asked questions

### What changed in Ruby 3.1 to cause Unknown alias?

Ruby 3.1 bundles Psych 4. In that version `YAML.load` behaves like `safe_load`: only basic types are allowed, and aliases are off by default. A file with `&anchor` and `*alias` or `<<:` merge keys raises `Psych::BadAlias` until the call opts in.

### Is aliases: true safe?

For files you control, yes. It only allows a document to refer back to a node it already defined, and the loader still refuses arbitrary Ruby objects. An alias can make a small file expand into a large structure, so keep it for configuration in your repository and leave it off for anything users can send you.

### Should I use YAML.unsafe_load instead?

Only where a file really stores Ruby objects, such as a cache of serialized records. It restores the old behaviour entirely, including instantiating whatever classes the file names. The agent uses it per call when that is what the file needs, names the file, and never applies it to input from outside.

### Does YAML.load_file need the same change?

Yes. `YAML.load_file` goes through the same safe loader and raises the same error on an aliased file. It accepts the same keyword, so `YAML.load_file(path, aliases: true)` loads it.

### The error comes from a gem, not my code. What does the agent do?

It reads the trace to find the gem and checks whether a newer release loads YAML with aliases enabled. If one exists, the pull request is a version bump with the proof. If none does, the result says so and offers the smallest patch that could be sent upstream or applied from a fork.

## More jobs like this: Fix a bug from an alert

- [Fix "Psych::DisallowedClass: Tried to load unspecified class" on Ruby 3.1 and later](https://getrush.ai/run/fix-psych-disallowedclass-tried-to-load-unspecified-class/ruby/)
- [Fix "PydanticImportError: BaseSettings has been moved to the pydantic-settings package"](https://getrush.ai/run/fix-pydantic-basesettings-import-error/pydantic/)
- [Fix "PydanticUserError: `regex` is removed. use `pattern` instead" in Pydantic 2](https://getrush.ai/run/fix-pydantic-regex-is-removed/pydantic/)
- [Fix Pydantic V1 Style @validator Validators Are Deprecated in a FastAPI App](https://getrush.ai/run/fix-pydantic-v1-style-validator-deprecated-warning/pydantic/)
- [Fix "AttributeError: cython_sources" When Installing PyYAML 5.4.1](https://getrush.ai/run/fix-pyyaml-cython-sources-attribute-error/pyyaml/)
- [Fix "LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy"](https://getrush.ai/run/fix-query-get-legacy-api-warning/flask-sqlalchemy/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
