docs(residency): document the Nix development environment architecture

- Rewrite the devShell notes around architectural responsibilities
- Clarify the boundaries between Nix, uv, and direnv
- Document lessons learned while debugging the BiteTrack devShell
- Simplify today's journal into findings and next steps
- Record the decision to manage native tooling through the Nix environment
This commit is contained in:
kiskaadee committed 2026-06-30 12:46:02 -05:00
1 parent 2591aca69a
commit 188d104860
3 files changed
+146 -87

No files matched your search

+61
View File
@@ -0,0 +1,61 @@
# Daily Journal: 2026-06-30
## Goal
Resume Milestone 0 by stabilizing the Nix development environment before implementing the first `/health` endpoint.
---
## Progress
Today's work focused entirely on debugging the Nix development environment.
The original blocker was that native binaries installed inside the UV virtual environment (notably Ruff) could not execute under NixOS because of dynamically linked executables.
Rather than enabling `nix-ld` globally, I decided to investigate a project-local solution using a declarative `flake.nix`.
---
## Findings
- Created a minimal `flake.nix` providing the project development shell.
- Learned how `eachDefaultSystem` exposes the shell for multiple architectures.
- Confirmed the shell loads automatically through `direnv`.
- Initially encountered a `glibc` symbol mismatch affecting Starship.
- The issue disappeared after removing `LD_LIBRARY_PATH` from the shell and relying on the standard Nix environment.
- Moved Ruff from the Python virtual environment into the Nix devShell.
- Confirmed:
```bash
ruff check .
```
passes.
```bash
uv run ruff check
```
also passes.
Pyright and pytest continue working from the Python virtual environment.
---
## Lessons Learned
- Native tooling belongs in the Nix environment.
- Python libraries belong in the virtual environment.
- The first component reporting an error is not necessarily the component causing it.
- Systematically testing hypotheses is more effective than searching for fixes.
---
## Next Session
Resume the original milestone:
- implement `/health`
- run Docker
- verify `/docs`
- complete Milestone 0 acceptance tests.
+55 -17
View File
@@ -1,36 +1,74 @@
# **The Anatomy of a devShell**
# The Anatomy of a devShell
In [[environments]] we briefly introduced the concept of a devShell.
## Motivation
A devShell is the Nix solution to the eternal development issue of "it works on my machine" at the system level.
If we get a little more technical, a devShell is a reproducible, isolated shell environment defined declaratively (usually via a `flake.nix`). It provides a specific set of system packages, compilers, and shared libraries without installing them globally.
With one important caveat: it is not primarily about installing packages. It is about reproducing an entire development environment. Rather than assuming the host machine already contains the correct compiler, linker, libraries, and development tools, a devShell declares those requirements explicitly and recreates them whenever the project is opened.
The problem it solves: "It works on my machine" syndrome and the lack of standard file-system paths on NixOS.
## Why I needed one
While bootstrapping BiteTrack, I discovered that several tools installed by `uv` did not execute correctly under NixOS. For example, Ruff is distributed as a native executable. The executable expected libraries (like `glibc`) to exist in standard Linux FHS locations (e.g., `/lib64/ld-linux-x86-64.so.2`) that do not exist on NixOS, causing:
Imagine a Python project requiring a concrete system-level library (e.g., `libpq` for PostgreSQL, `geos` for PostGIS, or specific versions of `gcc`), pip or uv will fail to compile native extensions because they cannot find these libraries in the standard paths like `/usr/lib`.
> `Could not start dynamically linked executable...`
When you run `nix develop` in that Python project's directory, Nix reads the declarative configuration (the `flake.nix`) and fetches or builds the exact versions of `libpq`, `geos`, and `gcc` specified. It stores them in the immutable `/nix/store`.
Instead of modifying my operating system with `nix-ld`, I decided to make the project self-contained by declaring its system dependencies inside a project-local `flake.nix`.
Then, rather than installing them globally, Nix drops you into a new, isolated bash shell. Behind the scenes, it intercepts and rewrites your environment variables—such as `PATH`, `LD_LIBRARY_PATH`, `C_INCLUDE_PATH`, and `PKG_CONFIG_PATH`—to point directly to those specific `/nix/store` paths.
## What a devShell Provides
A Nix devShell constructed via `mkShell` manipulates the shell environment to expose specific software and libraries without installing them globally.
Now, when you run `pip install` or `uv sync` inside this shell, the compiler seamlessly finds the required headers and libraries. It succeeds perfectly, regardless of whether you are on NixOS, macOS, or a completely clean Ubuntu installation.
* **System Executables (`PATH`):** Packages declared in `packages` (like `uv` and `ruff`) have their `/bin` directories prepended to `$PATH`. The shell uses the Nix store paths directly.
* **Shared Libraries:** Standard Linux distributions rely on global library paths. Nix compiles packages to look for their dependencies via absolute paths in the Nix store (using `RPATH`).
* **Environment Variables:** Standard builder variables are set automatically. Custom variables can be injected (e.g., `env.FOO = "bar";`), but manual manipulation of `LD_LIBRARY_PATH` often leads to symbol collisions if not handled carefully, as it overrides the explicitly linked `RPATH` of other Nix-provided binaries.
* **Compilers & Toolchains:** By providing `stdenv` or specific libraries (like `zlib`, `openssl`, `libffi`), the shell ensures that any tools compiled dynamically inside the environment (such as Python C-extensions) link against the exact library versions declared in the flake.
---
***Note**: Delaying this until it's really necessary during a project, or until Milestone 2 is completed*
## devShell and UV: Separation of Concerns
To avoid system-level conflicts, dependencies are strictly partitioned based on their execution requirements:
**Why This is a Game-Changer for Development**
| Component | Managed By | Rationale |
| :--- | :--- | :--- |
| `uv` executable | Nix | Requires native execution and dynamically linked system libraries. |
| `ruff` | Nix | Pre-compiled native Rust executable. Fails under FHS assumptions without `nix-ld`. |
| Compiler Toolchain | Nix | Provides `glibc`, `stdenv`, `libffi` for compiling native extensions. |
| System Libraries | Nix | OpenSSL, PostgreSQL (`libpq.so`) needed by Python packages at runtime. |
| Python Virtualenv | `uv` | Strictly isolates project-specific Python dependencies. |
| `pytest` | `uv` | Pure Python package/script; executes safely within the interpreter. |
| `pyright` | `uv` | Node-based but wrapped via PyPI; executes via the local interpreter environment. |
| FastAPI / App Code | `uv` | Core application logic; belongs in the isolated Python environment. |
## Why Not `nix-ld`?
**Creating your first devShell in NixOS**
A common workaround for dynamic linker issues in NixOS is enabling `nix-ld` in the declarative global configuration. `nix-ld` provides a shim at the standard FHS linker path that redirects executions to the Nix store.
**nix-ld**
* **Pros:** Fixes the whole machine. Pre-compiled binaries downloaded from the internet (via `uv`, `npm`, `cargo`) usually execute without modification.
* **Cons:** Requires global system configuration. Compromises the strict purity and reproducibility of Nix, as projects will suddenly rely on the host machine having `nix-ld` enabled rather than declaring their own dependencies.
**devShell**
* **Pros:** Strictly project-local and reproducible. Documents exact system requirements. Highly portable across any system running the Nix package manager (including macOS or Ubuntu via WSL).
* **Cons:** Requires an extra `flake.nix` file. Requires manually triaging which tools must be moved from standard package managers (like `uv`) into Nix.
## Lectures:
The commitment in the BiteTrack project is to achieve a declarative and reproducible environment. Using a devShell saves time for any hypothetical developer onboarding to the project by eliminating "environment-related" setup bugs.
[Easy development environments with Nix and Nix flakes!](https://dev.to/arnu515/easy-development-environments-with-nix-and-nix-flakes-21mb)
## Lessons Learned
[Declarative shell environments with `shell.nix`](https://nix.dev/tutorials/first-steps/declarative-shell.html)
* **Native executables and Python packages are different concerns:** Tools distributed as binaries (Ruff) belong in Nix. Tools executing strictly via the Python interpreter belong in `uv`.
* **A tool failing first is not necessarily the source of the bug:** The `glibc` symbol mismatch affecting Starship was a downstream casualty of manually forcing `LD_LIBRARY_PATH` into the environment.
* **`LD_LIBRARY_PATH` should not be modified casually:** It overrides library lookups globally for the shell, breaking tools that rely on specific, different versions of those libraries.
* **`direnv` simply loads the shell:** It is an orchestrator, not the underlying problem when a shell fails to load correctly.
* **A reproducible environment is easier to debug than a globally configured one:** Isolation prevents cross-contamination of dependencies.
[Making a dev shell with nix flakes](https://fasterthanli.me/series/building-a-rust-service-with-nix/part-10)
## Future Improvements
Investigate the following approaches to further optimize or simplify the Nix/Python bridge:
* `devenv.sh`
* `dream2nix`
* `uv2nix`
* `devenv` test support
* Managing multiple Python versions within the flake
## External Resources
* [Easy development environments with Nix and Nix flakes!](https://dev.to/arnu515/easy-development-environments-with-nix-and-nix-flakes-21mb)
* [Declarative shell environments with `shell.nix`](https://nix.dev/tutorials/first-steps/declarative-shell.html)
* [Making a dev shell with nix flakes](https://fasterthanli.me/series/building-a-rust-service-with-nix/part-10)
* [Development shells with Nix: four quick examples (2025)](https://michael.stapelberg.ch/posts/2025-07-27-dev-shells-with-nix-4-quick-examples/)
[Development shells with Nix: four quick examples (2025)](https://michael.stapelberg.ch/posts/2025-07-27-dev-shells-with-nix-4-quick-examples/)
+30 -70
View File
@@ -1,88 +1,48 @@
# devShells, direnv, env files and secret management
# Environment Management: devShells, direnv, and uv
With NixOS already providing `direnv`, when does it become necessary or advantageous to introduce `devShell`s? which responsibilities belong to each?
To answer this accurately, we must establish clear problem statement: managing software dependencies spans multiple layers —from system-level shared libraries to language-specific packages to environment variables. Relying on a single tool to handle all layers inevitably leads to fragile environments, specially on a non-FHS (Filesystem Hierarchy Standard) distribution like NixOS
Let's see an overview of these tools, understand what problems they solve, and how their responsibilities should be divided
## [uv: The Python Speed Demon](https://docs.astral.sh/uv/)
`uv` is powerful Python package and project manager. Just like `pip` or similar package managers like `npm` in the JavaScript ecosystem, `uv`'s primary's job is making sure every dependency used in your project is properly resolved, locked, and installed into an isolated virtual environment at lightning speed. It strictly handles the *language-layer* of your project.
If your project relies on pure Python code, `uv` is practically all you need. However, the illusion breaks the moment your Python package require compiling C-extensions or linking against native system libraries (think `numpy`, `pyscopg2`, or `cryptography`).
To build these packages, `uv` assumes your operating system follows traditional Linux conventions. It blindly reaches into standard directories like `/usr/lib` or `usr/include`, expecting to find compilers, headers, and C-libraries waiting for it. On NixOS, those FHS directories essentially do not exists. As a result, `uv` hits a brick wall, throwing a massive compilation error simply because it cannot find the system-level components it needs.
This is exactly where we need to step down a layer and bring our next tool to bridge the gap.
## Nix devShell (`nix develop`)
Think of a **devShell** as a temporary, isolated workshop for your project.
Many system-level libraries `uv` often crash trying to find them in NixOS. Instead of cluttering your OS with global installs, a devShell quietly rewires your terminal's environment variables (like `PATH` and `LD_LIBRARY_PATH`) to point directly to the exact dependencies you need.
**The Result:** Seamless, crash-free installations that succeed perfectly every time—whether you're on NixOS, macOS, or Ubuntu.
*(Expanded [[devShells]] guide coming soon.)*
## [direnv](https://direnv.net/)
If devShell is your workshop, `direnv` could be an automated assistant, who makes sure the tools are ready to use the second you walk through the door.
`direnv` is a shell extension that keeps a watchful eye on your directories. The moment you `cd` into a project folder containing an `.envrc` file, it automatically loads—or unloads- your environment variables and shell settings.
That way, you don't need to `source .venv/bin/activate` or each time you enter your project.
Managing software dependencies spans multiple layers—from system-level shared libraries, to language-specific packages, to environment variables. Relying on a single tool to handle all layers inevitably leads to fragile environments, especially on a non-FHS distribution like NixOS.
To maintain a reproducible architecture, responsibilities are strictly divided among three tools.
## The Responsibility Matrix
|**Tool**|**Scope**|**Responsibilities**|
|---|---|---|
|**Nix devShell**|System / OS level|Providing Python interpreters, C compilers, system libraries (e.g., PostgreSQL client libs), and non-Python CLI tools (e.g., `jq`, `docker`).|
|**uv**|Python userland|Resolving and downloading Python packages (FastAPI, SQLAlchemy), writing the lockfile, and managing the local `.venv`.|
|**direnv**|Workflow / Shell level|Automating the activation of the `devShell` and exporting runtime secrets/environment variables (e.g., `DATABASE_URL`).|
| Tool | Scope | Responsibilities |
| :--- | :--- | :--- |
| **Nix devShell** | System / OS level | Providing Python interpreters, C compilers, system libraries (e.g., `postgresql` client libs), and non-Python native CLI tools (e.g., `ruff`, `docker`). |
| **uv** | Python userland | Resolving Python packages (FastAPI, SQLAlchemy), writing the lockfile, and managing the local `.venv`. |
| **direnv** | Workflow / Shell level | Automating the activation of the devShell, the Python virtual environment, and exporting runtime secrets/environment variables. |
## When does it become advantageous to introduce devShells?
## Tool Overview
If you're developing a pure-Python script that relies on standard libraries or pure-Python packages, you can survive on NixOS with just `uv` (assuming you have a globally installed Python interpreter).
### 1. uv (The Package Manager)
`uv` handles the language layer. Its job is to resolve, lock, and install pure Python dependencies into an isolated virtual environment.
However, introducing a `devShell` becomes **necessary** (not just advantageous), under the following conditions:
*Boundary:* `uv` assumes a standard Linux environment. It cannot reliably manage or compile packages that require dynamically linked C-extensions or native system binaries on NixOS. *(See: Anatomy of a devShell for details on native dependency resolution).*
- **You require native C extensions:** The moment your FastAPI project interacts with databases using libraries like `psycopg` (PostgreSQL) or handles geospatial data (PostGIS), `uv` will attempt to build these from source or download manylinux wheels. On NixOS, dynamically linked manylinux wheels often fail to execute because the interpreter cannot find the required `.so` files. A `devShell` allows you to inject `stdenv.cc.cc.lib`, `zlib`, or `postgresql` directly into the environment's `LD_LIBRARY_PATH`.
- **You need reproducible system tools:** If your project requires a specific version of a database migration tool, a Node.js frontend build step, or a specific formatting tool, defining these in a `devShell` ensures any developer cloning the repository gets the exact same binaries.
- **You are collaborating across OS boundaries:** A `devShell` abstracts away the host operating system. A colleague on macOS or Ubuntu will get the same underlying system dependencies as you do on NixOS.
### 2. Nix devShell (The Workshop)
A devShell abstracts away the host operating system. Rather than installing libraries globally, it rewires the terminal's environment variables to point directly to the exact system dependencies required by the project.
### Analyzing the Trade-offs
*Boundary:* The devShell handles what the operating system *should* provide, ensuring any developer cloning the repository gets the exact same binaries, regardless of whether they use NixOS, macOS, or Ubuntu.
Choosing to implement this trifecta (`devShell` + `direnv` + `uv`) introduces specific trade-offs:
### 3. direnv (The Orchestrator)
`direnv` is a shell extension that watches directories. Upon entering a project folder with an `.envrc` file, it automatically loads the environment.
- **Complexity vs. Reproducibility:** * _Cost:_ You are introducing Nix syntax and flake evaluation into a Python project. Developers unfamiliar with Nix may struggle to update system dependencies.
- _Benefit:_ Absolute guarantee that the environment can be reproduced identically years from now.
- **Performance vs. Isolation:**
- _Cost:_ Evaluating a complex `flake.nix` takes time, though `nix-direnv` mitigates this heavily through caching.
- _Benefit:_ Total isolation. Your FastAPI project's dependencies will not bleed into or be corrupted by your host system's updates.
- **Maintenance Cost:** You now have two sources of truth for dependencies: `flake.nix` for system libraries and `pyproject.toml`/`uv.lock` for Python libraries. You must deliberately decide where a dependency belongs to avoid conflicts (e.g., do not install `ruff` via Nix if you are already managing it via `uv`).
*Boundary:* `direnv` does not install or build software. It simply answers the question: *"What environment variables and shells should be active right now?"* ## Analyzing the Trade-offs
---
## Should I use a devShell for BiteTrack
Choosing to implement this trifecta introduces specific trade-offs:
The project itself may require some PostgreSQL extension or package in the long run, but adding the complexity of a devShell now is overkill, a sensible approach is:
* **Complexity vs. Reproducibility:** * *Cost:* Introducing Nix syntax and flake evaluation into a standard Python project increases the cognitive load for developers unfamiliar with Nix.
* *Benefit:* Absolute guarantee that the environment can be reproduced identically years from now.
* **Maintenance Cost:** * *Cost:* There are now two sources of truth for dependencies: `flake.nix` for system libraries and tools, and `pyproject.toml`/`uv.lock` for Python libraries.
* *Benefit:* Total isolation. You must deliberately decide where a dependency belongs, preventing Python packages from corrupting system tools and vice versa.
- **Keep using `direnv` now.**
- Introduce `devShell` later, when the environment itself becomes part of the project.
## Environment Management in BiteTrack
A good mental model is:
BiteTrack utilizes all three tools in tandem.
- **`.envrc`** answers: _"What environment variables should be available?"_
- **`devShell`** answers: _"What software must exist on this machine to work on this project?"_
The initial bootstrapping attempt relied solely on `uv` and `direnv`. However, the environment hit a hard limitation when native developer tooling (specifically, the pre-compiled Rust binary for Ruff) crashed due to missing dynamic libraries on NixOS.
Right now the project is simple enough that `direnv` is sufficient. Once we face a brick-wall fighting with installing specific versions of tools like `uv`, PostgreSQL clients, Ruff, Pyright, or other binaries, a `devShell` will become valuable because anyone entering the project gets the exact same toolchain.
Instead of modifying the host OS, the project architecture was updated:
1. **`devShell`** provisions the native tools (`ruff`, `uv` executable) and core libraries.
2. **`uv`** manages the FastAPI application dependencies.
3. **`direnv`** silently orchestrates both upon entering the directory.