# Fix "TypeError: Descriptors cannot be created directly" in Python Protobuf

Yes. An agent regenerates the stale _pb2.py files, even when the .proto sources are missing, runs your tests on current protobuf, and opens a pull request.

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

## What the agent does

The agent first checks what a fresh install gives the project and where it stops. In a client library like NVIDIA/clara-platform-python-client, `requirements.txt` lists `grpcio` and `protobuf` with no versions and `setup.py` repeats them in `install_requires`. The package ships fourteen generated modules under `nvidia_clara/grpc/`: seven `_pb2.py` files, 7,795 lines between them, and seven `_pb2_grpc.py` files. A clean environment resolves protobuf 7.36.2, and the first import fails in `common_pb2.py` at line 50, on `_descriptor.FieldDescriptor(`. All four test modules under `tests/` fail at collection with the same `TypeError`.

The message offers two workarounds, and the agent tries both so the pull request can say what each costs. Pinning `protobuf==3.20.3` makes the 12 tests pass. Setting `PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python` makes them pass on 7.36.2 as well, using the slower pure-Python parser, and only for processes that remember to set it. Neither touches the cause, which is that the files were written by a `protoc` older than 3.19 and build their descriptors field by field in Python.

The real fix is to regenerate, and here the obvious route is closed: the repository contains no `.proto` files. The agent does not guess at schemas. Every old `_pb2.py` embeds its own compiled schema as `DESCRIPTOR.serialized_pb`. In the environment where the old files still import, the agent loads each module, parses those bytes as a `FileDescriptorProto`, and writes all seven into one descriptor set. The set names the original sources, such as `nvidia/clara/platform/jobs.proto`, and their imports of `common.proto` and `clara.proto`. Then it runs `python -m grpc_tools.protoc --descriptor_set_in=<set> --python_out=... --grpc_python_out=...` with those names, and the compiler emits fresh modules from the recovered schema.

Two adjustments make the output fit the package. The generator writes imports that follow the proto paths, `from nvidia.clara.platform import common_pb2`, while the package keeps its modules in `nvidia_clara/grpc/`, so the agent rewrites those import lines the way the originals were rewritten. It also restores the licence header the old files carry above the `Generated by the protocol buffer compiler` line. It adds the script that performs the dump and the regeneration to the repository, so the next maintainer has a command to run.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "This project fails with: TypeError: Descriptors cannot be created directly. If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0. Fix it properly. Read the dependency files and say how protobuf, grpcio and grpcio-tools are constrained. List every generated _pb2.py and _pb2_grpc.py file and say whether the .proto sources are in the repository. In a clean environment with the newest protobuf, reproduce the error and run the tests; quote the first traceback and the summary. Try both workarounds from the message (protobuf 3.20.x, and PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python on the newest protobuf) and report the test summary for each, but do not ship either as the fix. Regenerate the files with the newest grpcio-tools. If the .proto sources are missing, recover them from the generated code: under a protobuf version where the old modules import, read each module's DESCRIPTOR.serialized_pb into a FileDescriptorSet and pass it to protoc with --descriptor_set_in. Do not hand-write schemas. Fix the generated import paths to match the package layout, keep any licence header the old files had, and commit the regeneration script. Run the tests on the newest protobuf with no environment variable set. Then find the oldest protobuf runtime the new files import on, and set the protobuf requirement to that lower bound. Open a pull request with the traceback before, the three test summaries, and the regeneration command.",
  "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 that replaces the fourteen generated modules, adds one regeneration script and the descriptor set it reads, and edits the two places that declare the protobuf requirement. The diff is large and mostly deletion: the seven `_pb2.py` files shrink from 7,795 lines to 595, because modern generated code carries the serialized schema and builds classes from it at import instead of spelling every field out. The description says so up front, so nobody tries to read the generated diff line by line.

It reports four test summaries: 4 collection errors on a fresh install, 12 passed on each workaround, and 12 passed on protobuf 7.36.2 with the regenerated files and no environment variable. It also states the new constraint that regeneration brings. Generated files now check the runtime at import, and files produced by this compiler declare gencode version 7.35.1. On protobuf 6.33.0 they refuse to load with `Detected incompatible Protobuf Gencode/Runtime versions`. So `install_requires` gains a lower bound on protobuf, and the description names it.

That bound is the reviewer's decision. A library whose users are held on an older protobuf by another dependency may prefer to regenerate with an older `grpcio-tools`, which yields files that load on a wider range of runtimes. The script takes the compiler from the environment, so choosing differently means installing a different `grpcio-tools` and running it again.

## Run it on every CI job that fails with this TypeError

Unpinned protobuf means this breaks on a schedule you do not control, usually in CI on the first run after a new major release. Add an automation with a `github` trigger on `workflow_run.failure` to the Project that holds the repository, with the prompt above. The failed run's event is placed after the prompt. The agent does not take the event's word for the cause: it installs the project fresh and confirms that the tests fail with this `TypeError` before it changes anything, and if they fail some other way it says so and stops. Only work by a repository owner, member or collaborator fires a `github` trigger, and CI runs from forks never do.

For generated code that is vendored into many services, a sweep is quicker than waiting. List the repositories that contain `_pb2.py` files and start one run each through the API with the same prompt, with a `request_id` that is a UUID v5 of the repository name so a second pass starts no duplicates.

## Why run it on Rush?

The error message itself recommends two shortcuts, and both are one line, which is why so many repositories carry a `protobuf<=3.20` pin years later. Regenerating is more work on a laptop: it needs the right `grpcio-tools`, an environment where the old files still load, and the patience to fix import paths afterwards. When the sources are gone it also needs the descriptor trick, which few people have done before. The run does all of it in its own sandbox with clean installs, and the session transcript keeps each command and its output.

The result is checkable in a way a pin is not. The pull request shows the same tests failing before and passing after on the newest runtime, plus the one new failure mode regeneration introduces and the version bound that prevents it. A reviewer approves a schema that was recovered from the shipped code byte for byte, and can rerun the script to confirm the files come out the same.

## Frequently asked questions

### Can generated code really be rebuilt without the .proto files?

Yes. A `_pb2.py` file embeds the compiled form of its schema, and `protoc` accepts compiled schemas through `--descriptor_set_in` in place of source files. The regenerated modules describe exactly the same messages and services. What is lost is anything that only existed in the source text, such as comments.

### Is setting PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python acceptable in production?

It makes old generated code load by switching to the pure-Python implementation, which the protobuf message itself warns is much slower. It also has to be set in every process, including workers and scripts. The agent tests it so you know it is available as a stopgap, and does not make it the fix.

### Why does the regenerated code refuse older protobuf runtimes?

Current generated files call a version check at import, and the runtime must be at least as new as the compiler that produced the code. Regenerating with the newest compiler therefore raises your minimum protobuf. The agent finds that minimum by installing older runtimes until the import fails, and writes it into the requirement.

### We vendor _pb2 files generated by another team. Should we regenerate them ourselves?

Better to take new files from the team that owns the schema, so both sides stay in step. The agent reports where the files came from when the repository says, such as a submodule or a copy script. If the prompt confirms you own the copies, it regenerates them and commits the script that did it.

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

- [Fix "Psych::BadAlias: Unknown alias" When Loading YAML on Ruby 3.1](https://getrush.ai/run/fix-psych-badalias-unknown-alias/psych/)
- [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/)

## 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/)
