Pydantic settings review
Files and images attached to this public thread are only available to signed-in users.
Sign inReview of PR #46 (local only, nothing posted)
Tests pass locally (hatch run pytest tests/settings tests/test_fastapi.py: 201 passed). I compared the PR against fastenv/dotenv.py, fastenv/settings/starlette_config.py, tests/test_dotenv.py, tests/cloud/test_object_storage.py, and the existing docs. Short answer: the code is capable, but it reads like a port of pydantic-settings' internals rather than a fastenv module. The biggest craftsmanship losses are (1) every file source implemented twice, sync and async, (2) tests that assert on internals and sequence lists instead of outcomes, and (3) docs that read as a compliance statement rather than a tutorial.
Source: one async implementation, not two parallel ones
Your siblings have one I/O path. dotenv.py is async-only; StarletteConfig has a single async _load_files and the constructor wraps it with anyio.run. This PR implements file reading twice in five places: DotEnvSettingsSource._read_env_files vs load (sources 695-732), SecretsSettingsSource.__call__ vs load (sources 803-899), _ConfigFileSettingsSource._load_files vs load (providers 52-99), PyprojectTomlConfigSettingsSource.__init__ vs load (providers 171-212), and NestedSecretsSettingsSource._load_env_vars vs load (providers 298-377). Roughly a third of the two source modules is this duplication, and each pair has already drifted slightly (the sync secrets lookup goes through find_case_path, the async one inlines a different comparison).
I understand why: pydantic-settings compat requires Settings() to work inside a running loop (test_settings_inside_running_event_loop), so anyio.run is off the table. But the fix for that constraint doesn't have to be two implementations. Two options that keep one code path:
- Make sources lazy. Nothing reads files in
__init__;__call__reads synchronously andloadreads asynchronously, but both call the same_read(path_bytes)parsing step, and the only duplicated part is the one-line read. This also deletesDEFER_SETTINGS_IOentirely, because that ContextVar exists only to suppress the eager I/O the constructors currently do. - Or keep eager sync I/O and have
loadcall the sync reader withanyio.to_thread.run_sync. Less pure, but it is one implementation and still non-blocking.
Either way, the isinstance(x, (str, os.PathLike)) list-normalization appears 10 times and the directory walk for secrets appears 4 times. Those want a helper the way dotenv.py has _set_dotenv_source.
Source: the load() machinery is clever where fastenv is clear
BaseSettings.load needs cls(**values) to run a custom __init__ but skip source loading. The PR achieves this with a __new__ override, a _PreparedSettings dataclass, a _PREPARED_SETTINGS ContextVar, plus the separate DEFER_SETTINGS_IO ContextVar, with the rationale spread over four comments (pydantic_settings.py 95-110, 175-210, 263-268). It took me three reads. Nothing in dotenv.py or object_storage.py needs the reader to hold this much state in their head. If the lazy-sources change above lands, one ContextVar goes away. For what remains, a single _LoadContext object with a docstring describing the lifecycle (set in load, claimed in __new__, consumed in __init__) would be far kinder than two unrelated ContextVars.
Source: module layout and imports don't match the house
- fastenv has one module per integration:
starlette_config.py,object_storage.py. This PR adds threepydantic_settings*modules that mirror upstream'ssources/providerslayout. "Providers" and "sources" are both settings sources; the split exists to dodge a circular import, which the PR then dodges again with a function-local import in_settings_sources(pydantic_settings.py 331). Merge the file sources intopydantic_settings_sources.py, or move the "configured file without a source" warning out ofBaseSettings. pydantic_settings.pyuses relative imports;starlette_config.pyanddotenv.pyusefrom fastenv.utilities import ....- Siblings import modules (
import os,import dataclasses,os.PathLike,dataclasses.dataclass). The PR mixesfrom os import PathLike,from pathlib import Path,from dataclasses import dataclasswithimport dataclassesin the same package.from enum import Enuminside_enum_value(sources 545) should be at the top. - Siblings use targeted inline
# pyright: ignore[...]; the PR disablesreportAny/reportExplicitAnyfile-wide in all three source modules. dotenv.pyandstarlette_config.pylog every load and error throughfastenv.utilities.logger. The PR never logs. Reading a dotenv file, a secrets directory, or a TOML file should produce the samefastenv loaded ...line users already get.- Option resolution (
config.get(name, default) if value is None else value) is written inline about 15 times in the providers;PydanticBaseEnvSettingsSource._optionalready exists and the providers don't use it.NestedSecretsSettingsSource.__init__is 70 lines of this.
Source: docstrings and the public surface
ObjectStorageConfig has a paragraph docstring and reference URLs; every public function in dotenv.py is documented. Here, SettingsConfigDict declares 25 options with no documentation for any, and most public methods (get_field_value, __call__, explode_env_vars, next_field) have none. A short docstring per source class explaining what it reads and what it returns would match the house.
fastenv/__init__.py grows __all__ by 15 names, including NoDecode, ForceDecode, IncompleteFieldDefinitionWarning, InitSettingsSource, PydanticBaseSettingsSource. The root today exports a handful of names and the docs already model from fastenv.settings.starlette_config import StarletteConfig for the rest. I'd export BaseSettings, SettingsConfigDict, SettingsError, and parse_dotenv at the root and leave the sources in their module. Also, the from .dotenv import (...) reflow in __init__.py is diff noise; the single line fit.
Small readability nit in utilities.py: the conditional expression inside the tuple is harder to read than the original; a key assignment in the comprehension or a tiny helper would keep the parser's one-liner feel.
Tests: docstrings are intelligible but in a different voice
House docstrings say what is done and what is asserted: "Instantiate class DotEnv with a "key=value" string argument and assert that it is set in both os.environ and the DotEnv instance." PR docstrings are imperative one-liners that read like commit titles: "Prefer constructor values, then environment, dotenv, secrets, and defaults." Several name the feature without the expectation ("Support pyproject search limits, explicit paths, and root-level settings"). Rewriting to "Assert that ..." form would also expose the next problem.
Tests: too many behaviors per test, too little parametrize
45 of the new tests have _and_ in the name (test_dotenv.py has 12, and those are "args_and_kwargs", one behavior). test_pyproject_search_depth_explicit_file_and_root checks six scenarios across three classes; test_nested_secret_missing_and_size_limits checks six; test_secrets_async_decode_hooks_and_failure_cleanup checks three. When one assert fails you can't tell which behavior broke. The house pattern is one behavior per test with @pytest.mark.parametrize for variants, and the PR already does this well in test_dotenv_filtering and test_prefix_targets.
The largest win: the three sync/async file pairs (test_pydantic_settings / _async, _sources / _async_sources, _providers / _async_providers) repeat each other. conftest.py already shows the fix: object_storage_config is a parametrized fixture that runs each test across four clouds. A load_settings fixture parametrized over Settings(...) and await Settings.load(...) would roughly halve the test code and guarantee the two paths stay in sync.
Tests: 53 lines reach into internals; several assert exact sequences
- Internal state:
DEFER_SETTINGS_IO(imported in three test files),source._set_current_state,source.config["case_sensitive"] = True,source.env_vars["app_count"],canonicalize_inputs,deep_merge,cast(Any, Invalid.model_config)["secrets_dir_missing"] = "ignore-typo". Prefer configuring throughSettingsConfigDictor constructor args and asserting onSettings(...).model_dump(). - Thread identity:
threading.get_ident() != event_loop_threadin four tests and_guard_filesystemmonkeypatching eightPathmethods. The Starlette test file has one responsiveness test using the samePath.read_texttrick, which is a fine precedent; the PR multiplies it and adds assertions about whichosfunctions anyio happened to call ({"listdir", "scandir"} & operations). Those will break on an anyio upgrade without any fastenv regression. - Sequence lists:
calls == ["read", "construct", "validate"],allocations == [Settings, Settings],events == ["remote-start", "remote-end", "computed", "async-computed"]. Assert the outcome (count is 7, nested count is 7) and drop the choreography. - Exact messages: the docs say "exact error text is not a compatibility contract", yet tests match
'field "connection".*"EnvSettingsSource"',"must reference a directory","mutually exclusive", anderrors()[0]["type"] == "extra_forbidden". Matching the exception type and the field name is enough.
Tests: fixtures, shared models, and small style drift
- About 56 inline
class Settings(BaseSettings)definitions.Service/ProviderSettingsare copied verbatim betweentest_pydantic_settings_providers.pyand_async_providers.py;SourceSettingsis defined differently in_sources.pyand_async_sources.py. These belong inconftest.pyor a shared module, liketests/test_dotenv.pyexportingvariable_is_setfor the cloud tests. monkeypatch.setattr(os, "environ", {})as an autouse fixture replacesos.environwith a plain dict. The house idiom ismocker.patch.dict(os.environ, clear=True)(122 uses in test_dotenv.py). The Starlette tests already drifted tomonkeypatch, so this is your call, but swapping the object rather than clearing it is a hack.pytestmark = pytest.mark.anyioin two files, per-test@pytest.mark.anyioin the third; the house uses per-test.- Function-local imports in four tests (
from dataclasses import dataclass,from fastenv import IncompleteFieldDefinitionWarning); house puts everything at the top. @finalon test classes intest_object_storage.py; absent here.
Docs: a tutorial became a compliance statement
The dotenv docs and your Starlette section talk to the reader: "let's set up a virtual environment", "If you're already inside an async function, use ...", "For example, start with a .env file". The Pydantic section opens with "It is an original implementation based on the public pydantic-settings 2.15.0 API" and closes with a "Compatibility and verification" section containing "No pydantic-settings implementation or tests were copied", "Behavioral probes check the supported API without requiring every upstream export", and "preserving the migration contract". That is provenance for the PR description or CHANGELOG, not for someone trying to load a .env file. I'd delete the whole "Compatibility and verification" section and the first sentence of the intro, and lead with "Install fastenv[settings], change your import, done."
Three more things keep it from reading like the rest of the site:
- Feature lists instead of examples: "The environment and dotenv sources support case sensitivity, aliases,
AliasChoices,AliasPath, prefix targets, nested delimiters and maximum splits, empty-value filtering, null markers, enum names, and JSON decoding." The Starlette section shows each capability with a four-line snippet. Either show two or three of these (nested delimiter,_env_file=None, a custom source) or cut the list; users will try the pydantic-settings docs and it will work. - Repetition: the YAML/CLI/cloud-secrets exclusions are stated in the settings.md intro, "Custom and file sources", "Application command-line arguments", "Compatibility and verification", comparisons.md "Command-line interfaces", and comparisons.md "Differences from pydantic-settings". Say it once in comparisons.md and link to it.
- The comparisons.md CLI section is three dated paragraphs of pydantic-settings issue archaeology. The rest of that page is short bullets per project. Two or three bullets with links carry the same point.
Smaller: "Dotenv parsing and environment isolation" restates environment.md#tips, then has a floating one-line code block (settings = await Settings.load()) under a paragraph about DotEnv mutation that doesn't connect to the heading. The index.md changes are good; the quickstart now writes .env with DotEnv and loads it with BaseSettings, which is a nice bridge between the two halves of the package.
What I'd do first
If you only take three things: collapse the sync/async source duplication (lazy sources, delete DEFER_SETTINGS_IO), parametrize the tests over a sync/async loader fixture and move shared models to conftest.py, and cut the Pydantic docs section to the tutorial voice with the provenance moved to the PR. Everything else above is polish you can do incrementally.
I left the branch checked out locally at br3ndonland/pydantic-settings; no files changed and nothing was posted to GitHub.
Done. Commit bf43afb is pushed to br3ndonland/pydantic-settings (-302 lines net), the PR body bullet about async I/O is updated, and this thread is subscribed to CI for that commit.
What changed
DEFER_SETTINGS_IO is gone. No source reads files in its constructor anymore, so there is nothing to defer. Each file source has one synchronous reader (_load_env_vars or _read_files), and load() runs that same reader in an AnyIO worker thread, then hands the result to __call__:
def __call__(self) -> dict[str, Any]:+ """Read variables, unless `load` already did, then return field inputs."""+ preloaded = self._preloaded+ self.env_vars = self._load_env_vars() if preloaded is None else preloadedEvery call reads, matching load_dotenv. load() preloads in a worker thread and call consumes it, so subclass call overrides still apply to both entry points....+ async def load(self) -> dict[str, Any]:+ """Read variables in a worker thread, then return field inputs."""+ self._preloaded = await anyio.to_thread.run_sync(self._load_env_vars)+ try:+ return self()+ finally:+ self._preloaded = Noneget_field_value and the field loop moved up into PydanticBaseEnvSettingsSource, so EnvSettingsSource, DotEnvSettingsSource, SecretsSettingsSource, and NestedSecretsSettingsSource each contribute only a reader. SecretsSettingsSource now reads a directory once into a dict keyed by candidate name instead of scanning per field (secrets_paths and find_case_path deleted). A new configured_paths() helper replaces the four copies of str | PathLike | Sequence normalization. _ConfigFileSettingsSource got the same shape for JSON/TOML/pyproject.
Decisions to veto
- Worker threads instead of mirrored
anyio.Pathreaders.anyio.Pathis itself per-opto_thread, so one sync reader inrun_syncgives the same non-blocking behavior with zero duplicated code. It is the inverse ofStarletteConfig's pattern, but the sync side here must work inside a running loop (test_settings_inside_running_event_loop), so the sync reader has to be the primary. - Read on every call, no caching. I first tried "read once on first call,
load()refreshes," buttest_secrets_load_uses_async_io_and_preserves_alias_priorityexpectssource()to see new files afterload(), and reading per call matchesload_dotenv. - Read errors propagate raw. A
PermissionErrorfrom a secrets file is no longer wrapped inSettingsError('error getting value for field ...'), since the read happens before the field loop. Renamed that test totest_secrets_async_read_errors_allow_retry. - Cancellation semantics. A cancelled
load()now waits for the in-flight thread read to finish (AnyIO default) rather than abandoning it. The reload test now blocksPath.read_texton athreading.Eventand releases it after cancelling.
Verification
hatch run pytest --ignore=tests/cloud: 307 passed.tests/cloudneeds object storage credentials this orb lacks (errors in setup).hatch run coverage report:fastenv/settingsandtests/settingsat 100%; only the skipped cloud files pull the total below the gate.hatch run ruff check/ruff format: clean. basedpyright with the env python: 0 errors. prettier: clean.
Remaining review points not yet actioned: the module split, two ContextVars in pydantic_settings.py, logging, root exports, test docstrings and exact-message asserts, and docs tone.
Basedpyright is flagging an unused bool from the run_sync call in the reworked cancellation test, a warning I missed earlier when I only saw "1 warning" locally. I'm fixing it now.
CI failed on one basedpyright warning from my reworked cancellation test (unused bool result of await anyio.to_thread.run_sync(blocked_read.wait)), which cancelled the other matrix jobs. I assigned it to _, confirmed 0 errors/0 warnings locally, amended it into the commit, and force-pushed as b33e456. A new CI subscription will report the rerun here.
CI is green on b33e456: all four Python matrix jobs (3.11 to 3.14), CodeQL, and Vercel passed. The changelog and pypi jobs skipped as expected for a non-release push. No action needed.
Pushed as 89c1da0 "Merge async settings tests into sync test files". The three test_pydantic_settings_async*.py files are gone, net -756 lines, 307 -> 267 tests. CI subscription is set; PR body needed no change (its test bullet still describes the layout accurately).
Structure: one file per module, one async class per file
I followed the test_starlette_config.py pattern rather than parametrizing tests over sync/async. Behavior tests run once through source() or Settings(), and a dedicated class at the end of each file (TestAsyncSourceLoading, TestSettingsAsyncLoading) holds only what exists inside an event loop: worker-thread reads keeping the loop responsive, reload after cancellation, load() honoring a __call__ override, awaitable custom sources, constructor/validator behavior under Settings.load(), and task-group concurrency. The one exception is the ZIP resource test in providers, which became async so its thread assertion covers _ConfigFileSettingsSource.load, the only async code path in that module.
Async-only coverage that I folded into existing sync tests instead of dropping: dotenv env_file_encoding, dotenv null/empty markers, alias order beating directory order for secrets, decode_complex_value, JSON/TOML decode errors, TOML non-table selections, secrets_prefix, and the cumulative size-limit growth case (which replaced the single-file version).
Decisions to veto:
- Dropped entirely as covered elsewhere or testing the old caching design: the "callers can mutate output safely" asserts, the
__new__allocation-count test, the PermissionError-then-retry test (unwrapped read errors behave the same onsource()), and the "sync model constructed insidesettings_customise_sources" test. The merged nested-instances test covers the real bypass risk (instances created by a constructor or validator duringload()still read their own sources). - Precedence is not re-tested through
Settings.load(). One test assertsawait Settings.load(**options) == Settings(**options)for the full option set, which is the "both entry points agree" check.
−with pytest.raises(− SettingsError, match='field "connection".*"EnvSettingsSource"'−) as error:+with pytest.raises(SettingsError, match="connection") as error: _ = EnvSettingsSource(SourceSettings)()assert isinstance(error.value.__cause__, ValueError)Loosened asserts now match a field name or a single keyword ("items", "service", "json_file", "Settings.load", "pending"), and the ValidationError check in test_constructor_environment_options_are_instance_specific compares error locs only, dropping Pydantic's int_parsing type code. I left extra_forbidden and "mapping"/"maximum size" matches since they distinguish behaviors, not wording.
Verification: ruff check/format clean, 267 passed (the one warning is the pre-existing Starlette httpx deprecation), coverage 100% on every fastenv/settings and tests/settings file, basedpyright 0 errors 0 warnings.
Remaining review points from the original list: path-normalization/module split of pydantic_settings_sources.py, the two ContextVars in pydantic_settings.py, logging, root exports, and docs tone.
CI is green for 89c1da0: all four Python versions (3.11-3.14), CodeQL, and Vercel passed. Nothing to fix.
The short version: there is no behavioral difference in the file reads themselves. anyio.Path is a thin wrapper that sends each pathlib.Path method to a worker thread. The trade-off is about where the thread boundary sits and which side of the API is the "real" implementation.
What anyio.Path actually does
Every async method on anyio.Path is await to_thread.run_sync(self._path.<method>, ...). In the installed anyio, read_text is literally to_thread.run_sync(self._path.read_text, encoding, errors, limiter=self._limiter), and iterdir wraps the generator the same way. So "mirrored anyio.Path readers" and "one sync reader in run_sync" both end up running pathlib calls on anyio's default thread pool. The bytes read, the encoding handling, and the errors raised are identical.
Where the two designs differ
Granularity of thread hops. The secrets source does exists(), is_dir(), iterdir(), then is_file() and read_text() per secret (pydantic_settings_sources.py). With anyio.Path that is one thread hop per call, so a directory with 20 secrets is roughly 43 hops, each one a loop round trip plus a CapacityLimiter acquisition. The current load makes exactly one hop for the whole _load_env_vars. Same for dotenv (is_file/is_fifo/read_text per file) and the providers (is_file/read_text per file). One hop is cheaper, but for settings loaded once at startup the difference is not something a user would notice.
Cancellation. anyio.Path gives you a cancellation point between every filesystem call. One run_sync gives you one: if the task is cancelled mid-read, the thread finishes its work and the result is discarded. For a handful of small files this is fine, but it is a real semantic difference.
Package resources. JsonConfigSettingsSource and friends accept importlib.resources Traversable objects, which only have sync is_file() and read_text(). anyio.Path only wraps pathlib.Path, so a mirrored async reader would still need a sync fallback for resources, which is the reason the providers load docstring calls this out. That source could not have been fully mirrored anyway.
Which side is primary. This is the real reason for the inversion. StarletteConfig.__init__ is the secondary path: it calls anyio.run around the async _load_files, which means the constructor cannot run inside an event loop, and test_starlette_config_constructor_in_running_event_loop asserts exactly that RuntimeError. For pydantic-settings that would be a compatibility break: BaseSettings() with env_file is routinely called at import time or inside FastAPI startup handlers, and test_constructor_and_load_agree_inside_running_event_loop pins that Settings(**options) works inside a running loop. So the sync reader has to be the primary implementation, and load wraps it rather than the reverse. StarletteConfig can afford anyio.run because its constructor is new API with no existing callers.
Blocking the loop. One consequence worth knowing: Settings() inside a running loop reads files synchronously on the loop thread. That is what pydantic-settings itself does and what the test expects, so it is the right behavior, but await Settings.load() is the only way to get the reads off the loop thread. The load docstring says "File sources read in worker threads," which covers it.
My read on the trade
Mirroring would buy finer cancellation and a closer resemblance to StarletteConfig, at the cost of a second copy of every reader (dotenv, secrets, config files) that still needs sync fallbacks for Traversable. Since anyio.Path would do the same run_sync underneath, I would keep the single-reader design. If you want the StarletteConfig parallel to be more visible, the one small change I would consider is a sentence in the PydanticBaseEnvSettingsSource.load docstring explaining why this side is inverted (the constructor must work inside a running loop), so a future reader does not try to "fix" it.
The docstring note is in 4491ad4, and the Pydantic half of docs/settings.md is rewritten in fc98b38. Both are pushed, and CI is running on fc98b38.
What was wrong with the tone
The section read like a specification:
- It opened with compatibility language.
- It listed about fifteen features in one paragraph without showing any of them.
- It explained
Settings.load()in the middle of the dotenv parser notes. - It ended on provenance and test-coverage caveats.
The Starlette section on the same page addresses the reader as "you" and leads with examples, so I matched that.
What changed
- Getting started: a
.envfile, a model, and the values that come out. - Two ways to load settings: when to use
Settings()and when to useawait Settings.load(), mirroring Starlette's "Two ways to load files". It says plainly that the constructor works inside a running loop but blocks it. - Sources and priority: an override example, plus a short explanation of secret files, which were on the priority list but never explained.
- Naming settings: the feature paragraph became one line per option plus an alias example.
- Dotenv parsing: its own section. The heading was renamed, so I updated the anchor in docs/comparisons.md.
- Writing your own source: an async function source example.
- Coming from pydantic-settings: replaces "Compatibility and verification" and starts with the import change.


Verification
- I ran every Python block in the section in order against the current code with warnings as errors. Each output comment matches what the block prints.
- That run only defines the classes in the TOML source, async source, and alias blocks. I confirmed their behavior with equivalent scratch scripts.
zensical buildreports no issues, and all anchors I link to exist in the built HTML.- Prettier, cspell, ruff and the 267 tests pass locally. I did not rerun basedpyright or coverage, since the only code change is a docstring.
Decisions to veto
- New gotcha documented. A dotenv name that matches no field raises
extra_forbidden, so a.envshared with other tools needsextra="ignore". This is easy to hit, so I gave it a paragraph. - Plain code blocks, no
!!!exampleadmonitions. I matched the Starlette section on the same page, notdotenv.md. Say so if you want the admonition style. - Options as a list, not a table. The site CSS breaks long code names mid-word in narrow table columns (
env_prefix_targe/t). The existing sources table has the same problem withPyprojectTomlConfigSettingsSource, and I left it alone. - Provenance kept but shortened. "Original implementation, written from the public documentation and signatures. No pydantic-settings code or tests were copied." stays as two plain sentences.
- Caveats dropped or reworded. I removed the
fastenv.__version__sentence, which the comparisons page already covers. "Not proof of exhaustive equivalence" became "try out the settings you rely on when you migrate." - CLI history in
comparisons.mdleft alone. It is a long dated chronology of upstream PRs that reads more like a memo than the rest of that page. You have edited that file recently, so I did not touch it.
The remaining points from the original review are the root exports, splitting pydantic_settings_sources.py, the two ContextVars, and logging.
CI is green for fc98b38: ci passed on Python 3.11 through 3.14, and CodeQL and the Vercel docs deploy succeeded. No action needed.
The remaining review points are the root exports, splitting pydantic_settings_sources.py, the two ContextVars in pydantic_settings.py, and logging.
There was only one ContextVar left to collapse: DEFER_SETTINGS_IO already went away with the lazy-sources commit, and my "two ContextVars" label was stale after that. What remained was the machinery around _PREPARED_SETTINGS, so I simplified that instead, in f222a7a.
load() now creates the instance itself and stores it in the ContextVar, and __init__ skips sources only for that exact instance. That removes the __new__ override, the _PreparedSettings dataclass and the mid-__init__ "consume" step. pydantic_settings.py is 17 lines shorter.
+settings = cls.__new__(cls)+token = _LOADED_SETTINGS.set(settings)try:− # Custom constructors receive the ordinary, still unvalidated inputs.− return cls(**state.values())+ settings.__init__(**state.values())finally:− _PREPARED_SETTINGS.reset(prepared_token)+ _LOADED_SETTINGS.reset(token)+return settingsThis replaces cls(**state.values()). It is the same two steps type.__call__ runs, except __new__ gets no arguments, which is how Pydantic itself calls it in model_construct.−prepared = _PREPARED_SETTINGS.get()−if prepared is not None and prepared.instance is __settings_self__:− # Consume the bypass before validation can construct nested models.− _ = _PREPARED_SETTINGS.set(None)+if _LOADED_SETTINGS.get() is __settings_self__: super().__init__(**values)The old code cleared the ContextVar here. An identity check makes that unnecessary, because nested or sibling instances are never the stored one.Decisions to veto:
- I kept the ContextVar rather than a private keyword argument. A custom
__init__(self, count)cannot accept an extra keyword, andtest_load_constructs_and_validates_oncecovers that case. - A subclass
__new__with required arguments no longer works withload(). I judged this acceptable because Pydantic's owncls.__new__(cls)calls already break such a class. - A validator that calls
self.__init__()duringload()would now skip sources. I did not guard against it, because the same validator recurses forever with the plain constructor.
Verification: all 267 tests pass with no test changes, and coverage stays at 100% for the settings files. Ruff is clean, and basedpyright reports 0 errors and 0 warnings. A scratch script ran 20 concurrent load() calls on a class with a custom __new__, a custom __init__ and an async source. Each call got its own correctly loaded instance, and the ContextVar was None afterward.
The PR description needed no change. CI for f222a7a is running and will report here.
CI is green for f222a7a: ci passed on Python 3.11 through 3.14, and CodeQL and the Vercel docs deploy succeeded. No action needed.
The remaining review points are the root exports, splitting pydantic_settings_sources.py, and logging.
They only partly match: my three-item list was a lossy compression of that section. One item was inverted, one came from a different section, and four of the section's six bullets were dropped.
| Original bullet | In my list as | State of the code now |
|---|---|---|
1. Three pydantic_settings* modules: merge the providers into the sources module, or move the "configured file without a source" warning out of BaseSettings |
"splitting pydantic_settings_sources.py" (wrong direction) |
Open |
2. Relative imports instead of from fastenv... |
dropped | Open in pydantic_settings.py and the providers module |
3. from x import y style and function-local imports |
dropped | Mostly open |
4. File-wide # pyright: reportAny=false |
dropped | Open in all three modules |
5. No logging through fastenv.utilities.logger |
"logging" | Open |
6. Option resolution written inline instead of using _option |
dropped | Open |
| Original bullet | In my list as | State of the code now |
|---|---|---|
1. Three pydantic_settings* modules: merge the providers into the sources module, or move the "configured file without a source" warning out of BaseSettings |
"splitting pydantic_settings_sources.py" (wrong direction) |
Open |
2. Relative imports instead of from fastenv... |
dropped | Open in pydantic_settings.py and the providers module |
3. from x import y style and function-local imports |
dropped | Mostly open |
4. File-wide # pyright: reportAny=false |
dropped | Open in all three modules |
5. No logging through fastenv.utilities.logger |
"logging" | Open |
6. Option resolution written inline instead of using _option |
dropped | Open |
- "Splitting" was wrong. The original suggestion was to merge, not split. The label drifted from "the module split" (sources versus providers) into "splitting" as I carried it between turns.
- "Root exports" is from a different section, "Source: docstrings and the public surface". It is still open:
fastenv/__init__.pyexports 15 Pydantic names. The suggestion was to keepBaseSettings,SettingsConfigDict,SettingsErrorandparse_dotenvat the root. - Bullet 1 had a claim that does not hold for the current code. I wrote that the split "exists to dodge a circular import". The providers module imports only from the sources module, so there is no cycle. The function-local import in
_settings_sourcescould move to the top of the file as it stands. - Bullet 1 has a size cost. Merging gives one module of about 1,130 lines.
object_storage.pyis 892, so there is precedent, but it is a judgment call. - Bullet 3 is partly done.
from dataclasses import dataclasswent away with the last commit.from os import PathLikeandfrom pathlib import Pathremain, andfrom enum import Enumis still inside a method. - Bullet 6 is untouched. The providers module has 16 inline
config.get(...)resolutions and no_optioncalls, most of them inNestedSecretsSettingsSource.__init__.
So the accurate remaining list is all six bullets above, plus root exports from the neighboring section.
Yes. Two modules: pydantic_settings.py keeps BaseSettings and SettingsConfigDict, and pydantic_settings_sources.py holds every source, with pydantic_settings_providers.py deleted.
I would not go to one module. The remaining boundary is a real one: BaseSettings imports the sources and nothing flows back. A single file would be about 1,470 lines.
The original bullet also offered a three-module alternative (move the warning out of BaseSettings). I would drop that option, because it only made sense if there were an import cycle, and there is none.
What the merge would touch:
- Imports: only three places import the providers module:
fastenv/__init__.py, the function-local import inpydantic_settings.py(which moves to the top), and one test file. The docs do not reference the providers module path. - Duplicates that would sit side by side:
_merge_datain the providers anddeep_mergein the sources are both recursive dict merges, and_CONFIG_DEFAULTandENV_FILE_SENTINELare bothPath(""). I have not yet checked whether each pair can collapse into one. - Tests:
tests/settings/test_pydantic_settings_providers.py(167 lines) would fold intotest_pydantic_settings_sources.pyif you want test files to mirror modules, astests/test_dotenv.pymirrorsfastenv/dotenv.py. That is your call.
The cost is a sources module of about 1,130 lines, compared with 892 for object_storage.py.
The providers module is gone, merged into pydantic_settings_sources.py in 91ad2d0. The Pydantic integration is now two modules, and test_pydantic_settings_providers.py is folded into test_pydantic_settings_sources.py.
The four source classes moved without changes to their logic, apart from the two duplicate pairs I flagged. Both pairs collapsed:
_merge_datais replaced by the existingdeep_merge. The only difference was that_merge_datadeep-copied values, which is unnecessary now that config files are parsed fresh on every read. A scratch script merged 5,000 random sets of nested documents both ways and got identical results.- Three
Path("")sentinels became oneDEFAULT_PATH. It replacesENV_FILE_SENTINEL,_CONFIG_DEFAULTand_ENV_FILE_DEFAULTinpydantic_settings.py.
Decisions to veto:
DEFAULT_PATHreplaces upstream's nameENV_FILE_SENTINEL. The old name would have been misleading for the JSON and TOML sources. Nothing in the docs or root exports referenced it.NestedSecretsSettingsSourcesits right afterSecretsSettingsSource, with the config file sources last. The test classes follow the same order.- Test names drop the word "provider".
ProviderSettingsbecameFileSettings, and the classes becameTestNestedSecretsSourceandTestConfigFileSourcesto match their neighbors. Test bodies are otherwise untouched. - The folded tests now run under the sources file's autouse fixture, which empties
os.environ. They pass with it. - The
deep_merge: boolconstructor parameter now shadows thedeep_mergefunction inside the JSON and TOML__init__bodies. The function is not called there, so I left the upstream-compatible parameter name alone. - Imports in
pydantic_settings.pyare still relative. I left that for the import-style bullet.
The size cost is as predicted: pydantic_settings_sources.py is 1,101 lines and the test file is 1,183.
Verification: the same 267 tests pass, coverage stays at 100% for the settings files, Ruff is clean, and basedpyright reports 0 errors and 0 warnings. The Python blocks in the settings docs still run. The PR description never named the providers module, so it needed no change.
CI for 91ad2d0 is running and will report here.
The CI failure on 91ad2d0 was not caused by the merge: one live Backblaze B2 upload returned a 500 on Python 3.11.
FAILED tests/cloud/test_object_storage.py::TestObjectStorageClientIntegration::test_upload_from_file_with_object_storage_config[object_storage_config2-None-PUT]
httpxyz.HTTPStatusError: Server error '500 '
1 failed, 407 passed, 6 skipped
The other 15 Backblaze upload and download cases in that job passed, as did every settings test. Python 3.12 passed in full, and 3.13 and 3.14 were cancelled by fail-fast, not failed.
I reran the failed and cancelled jobs (attempt 2 is in progress) and subscribed this thread to the result. No code changed.
The remaining review points are unchanged: the import cleanups, _option in the nested secrets source, logging, and the root exports.
CI is now green on 91ad2d0: the rerun passed on Python 3.11, 3.13, and 3.14, and 3.12 had already passed. The same code passing confirms the earlier failure was the transient Backblaze 500, not the module merge.
The remaining review points are the import cleanups, _option in the nested secrets source, logging, and the root exports.
Yes. pydantic-settings spells it settings_customise_sources, British "s" and all, and there is no customize alias.
I checked against pydantic-settings 2.16.2 in a scratch environment (it is not a dependency of this repo): BaseSettings.settings_customise_sources is a classmethod defined in pydantic_settings/main.py, and it is the only attribute on the class with "custom" in a public name.
fastenv/settings/pydantic_settings.py matches it exactly, with the same name and the same five parameters in the same order: settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings. So a class that overrides the hook for pydantic-settings works unchanged with fastenv.BaseSettings.
The spelling is upstream's, so I'd keep it. The prose in docs/settings.md only uses the word inside the method name, so there is no clash with the American "customize" used elsewhere in the docs.
The absolute imports and import os style are done and pushed in ec6ee7d. I left the file-level Pyright comments in place, because targeted ignores turned out to be the wrong fix.
Why the Pyright comments stayed
Without the two file-level comments, basedpyright reports reportAny or reportExplicitAny on 186 lines: 24 in pydantic_settings.py and 162 in pydantic_settings_sources.py. An inline ignore on each would be far noisier than one comment per file. My original review point compared these modules to siblings that have at most three Any sites each, so it understated the cost.
The Any is mostly deliberate. The source hooks (get_field_value, prepare_field_value, decode_complex_value, __call__, current_state) carry the same Any annotations as pydantic-settings 2.16.2, which I checked.
The alternative is to retype values as object, the way StarletteConfig.file_values does. A mechanical swap, which I tried and reverted, leaves 66 lines to fix with narrowing or casts. It also makes the public hook signatures differ from upstream. I'd keep the comments, but that is your call.
What changed
- Absolute import:
pydantic_settings.pynow importsfrom fastenv.settings.pydantic_settings_sources. - Module imports:
os.PathLike[str]replacesfrom os import PathLike, andenum.Enumreplaces the import inside_enum_value. - Tests: the four imports inside test functions moved to the top of their files.
- Comment placement: the Pyright comments in the sources module and its tests now sit at the top of the file, as in
pydantic_settings.py.
Locally, 267 tests pass, the settings files are at 100% coverage, ruff is clean, and basedpyright reports 0 errors and 0 warnings. CI for the push is pending. The PR description needed no change.
Decisions to veto
- I used
import enumwithenum.Enum, matchingimport dataclassesin the same module, not a top-levelfrom enum import Enum. - I left
from pathlib import Path,from abc import ..., andfrom collections import Counteralone. Converting them touches about 25 more lines. - The sources test now imports
IncompleteFieldDefinitionWarningfrom the sources module, like its other imports, not fromfastenv. - I collapsed the six-name
typingimport in the sources module onto one line.
Do you want to keep the file-level Pyright comments, or should I retype the values as object?
CI is green on ec6ee7d: all four Python versions, CodeQL, and the Vercel docs build passed.
The open question is unchanged: keep the file-level Pyright comments, or retype the values as object?
NestedSecretsSettingsSource.__init__ now resolves every option with _option, pushed as f88f60c (28 insertions, 46 deletions). CI is running and will report here; the PR title and body needed no change.
_option reads self.config, which only exists after super().__init__, so the constructor now calls the parent first and layers the secrets_* options on top of what the parent resolved.
+if case_sensitive is None:+ case_sensitive = getattr(wrapped, "case_sensitive", None)+if env_prefix is None:+ env_prefix = getattr(wrapped, "env_prefix", None)+super().__init__(+ settings_cls, case_sensitive=case_sensitive, env_prefix=env_prefix+)The wrapped source only supplies fallbacks for these three arguments, so the parent can resolve them from config as usual.+self.case_sensitive: bool = self._option(+ "secrets_case_sensitive", secrets_case_sensitive, self.case_sensitive+)The parent's resolved value is the default, which gives the two-key fall-through (secrets_case_sensitive, then case_sensitive) in one call.Verification
- Old versus new constructor: a scratch script (since deleted) compared the resolved attributes or raised error across 699,504 combinations of arguments, config, and wrapped sources. There were 0 differences, and 333,716 of the combinations exercised the
SettingsErrorpaths. - Checks: 267 tests pass, the settings files stay at 100% coverage, ruff is clean, and basedpyright reports 0 errors and 0 warnings.
Decisions to veto
_optionnow skipsNoneconfig values. It wasself.config.get(name, default), which returns an explicitNonefrom config instead of the default. Without the change,SettingsConfigDict(secrets_prefix=None)would have stopped falling through toenv_prefix, which the old code and pydantic-settings both do. This applies to every caller: for example,env_parse_enumsnow resolves toFalseinstead ofNoneunder the default config (both falsy, no test or code distinguishes them).secrets_dir_missingusesis Noneinstead ofor. Two edge cases change, both now matching pydantic-settings 2.16.2: an empty-string argument is rejected instead of falling back to config, and an explicitNonein config means"warn"instead of raising.- I added a one-line docstring to
_option, since its three-step precedence is now what the nested secrets source leans on.
The dotenv, JSON, TOML, and pyproject sources still resolve their options inline with config.get(...) before super().__init__; I left them alone since you only named the nested secrets source. The remaining review points are logging and the root exports.
CI is green on f88f60c: tests pass on Python 3.11 through 3.14, and CodeQL and the Vercel deployment succeeded. No action needed.
Changing them is not one uniform edit. Only the dotenv source is a clean fit for _option, and the payoff there is consistency, not fewer lines. I made no edits.
Dotenv: a clean fit, two options
DotEnvSettingsSource.__init__ already inherits _option. Its three options are not passed to the parent, so super().__init__ can move to the top with no ordering risk. Then env_file_encoding and dotenv_filtering become one _option call each.
The one behavior change is that both use or today, so an empty string falls back to config. With _option, an empty string is kept. pydantic-settings 2.16.2 uses is not None for both, so this moves toward upstream, the same as secrets_dir_missing did.
File paths: _option cannot express them
env_file, json_file, and toml_file use the DEFAULT_PATH sentinel because None is a real value meaning "read no file". _option treats None as unset, so Settings(_env_file=None) would silently start reading the configured file again. These three have to stay inline.
JSON and TOML: two structural obstacles
_optionis out of reach. It lives onPydanticBaseEnvSettingsSource, and_ConfigFileSettingsSourcedoes not inherit from it. It would need to move up toPydanticBaseSettingsSource.- The resolved values are parent constructor arguments.
JsonConfigSettingsSourcepasses the file and encoding intosuper().__init__, but_optionneedsself.config, which only exists after that call. The nested secrets trick of calling the parent first does not work without the child overwriting the parent's private_filesand_encoding.
All that would convert only json_file_encoding and toml_table_header. The pyproject source fits worst: its two options have no constructor argument, so the call would be _option(name, None, default).
A related bug in the same lines
Fastenv reads JSON and dotenv files with the locale encoding when no encoding is set, while pydantic-settings defaults to UTF-8. I confirmed it by forcing an ASCII locale (PYTHONUTF8=0 LC_ALL=C) on a UTF-8 file containing olá:
| JSON | dotenv | |
|---|---|---|
| fastenv | UnicodeDecodeError |
UnicodeDecodeError |
| pydantic-settings 2.16.2 | {'name': 'olá'} |
{'name': 'olá'} |
| JSON | dotenv | |
|---|---|---|
| fastenv | UnicodeDecodeError |
UnicodeDecodeError |
| pydantic-settings 2.16.2 | {'name': 'olá'} |
{'name': 'olá'} |
This mostly bites on Windows, where the locale encoding is usually not UTF-8. TOML is unaffected because it uses the parent's "utf-8" default.
The fix does not need _option: fall back to "utf-8" at the two read sites, as pydantic-settings does. That also keeps self.env_file_encoding as None when unset, matching upstream.
Recommendation
Convert the dotenv source and fix the UTF-8 default, and leave JSON, TOML, and pyproject inline. For those three, the structural churn buys two converted lines.
Both changes are pushed as two commits: 6379eaf converts the dotenv source to _option, and e553ee0 fixes the UTF-8 default. CI for e553ee0 is still running.
Local checks on the final tree: 268 tests pass, the settings files stay at 100% coverage, ruff is clean, and basedpyright reports 0 errors and 0 warnings. The new regression test fails on the old code, and also fails if any one of the three read-site fixes is reverted.
Decisions to veto:
- Secret files are now read as UTF-8 too. I only named dotenv and JSON in the walk-through, but
SecretsSettingsSourcehad the same locale-encoding read, and pydantic-settings reads secrets as UTF-8. - The fallback sits at the read site.
env_file_encodingandjson_file_encodingstill resolve toNonewhen unset, as upstream. A side effect is that an empty-string encoding also reads as UTF-8. - Empty-string arguments no longer fall back to config.
env_file_encoding=""ordotenv_filtering=""passed toDotEnvSettingsSourcenow wins overmodel_config, because_optionchecksis not None. - The regression test runs a child interpreter. The locale is process-wide, so
test_files_are_read_as_utf8_in_other_localesin tests/settings/test_pydantic_settings.py sets an ASCII locale in a subprocess. I believe it passes trivially on macOS, where the locale encoding is always UTF-8, but it is a real check on the Ubuntu CI runners. - Two commits. I kept the
_optionrefactor separate from the bug fix.
+self.env_file: Any = (+ self.config.get("env_file") if env_file == DEFAULT_PATH else env_file+)+self.env_file_encoding: str | None = self._option(+ "env_file_encoding", env_file_encoding+)env_file stays inline: None means "no dotenv file", so it needs the DEFAULT_PATH sentinel that _option cannot express.−contents = path.read_text(encoding=self.env_file_encoding)+contents = path.read_text(encoding=self.env_file_encoding or "utf-8")The attribute stays None when unset; only the read falls back, so "" also reads as UTF-8.No docs or PR description changes were needed: neither states a default encoding. The remaining review points are logging in the Pydantic sources and trimming the root exports.
CI passed for e553ee0: the tests on Python 3.11 to 3.14, CodeQL, and Vercel all succeeded (pypi and changelog were skipped). No action needed.
The remaining review points are logging in the Pydantic sources and trimming the root exports.
The root now exports only BaseSettings, SettingsConfigDict, SettingsError, and parse_dotenv from this PR, pushed as a7debfd. CI is running.
Local checks: 268 tests pass, fastenv/init.py and the settings files are at 100% coverage, ruff and prettier are clean, and basedpyright reports 0 errors and 0 warnings. I also ran the updated TOML docs example and it read service.toml.
Decisions to veto:
- Docs now import sources from
fastenv.settings.pydantic_settings_sources. In docs/settings.md, I changed the TOML example and added a line above the sources table and to theNoDecode/ForceDecodeparagraph. - The migration note changed. "Change
from pydantic_settings import ...tofrom fastenv import ..." was no longer true, so it now lists which names come fromfastenv, which from the sources module, and that the rest still come frompydantic. test_public_settings_exportschecks only the three root names. I did not add an assertion that the source classes are absent from the root.- The
.dotenvimport is back on one line. The PR had reformatted it for no reason, so the root diff against the base branch is now additions only.
IncompleteFieldDefinitionWarning is no longer reachable from the root and is not mentioned in the docs.
The PR description needed no change. The last open review point is logging in the Pydantic sources.
CI passed for a7debfd: the tests on Python 3.11 to 3.14, CodeQL, and Vercel all succeeded (pypi and changelog were skipped). No action needed.
The last open review point is logging in the Pydantic sources.
You are right: the 15 root exports were exactly pydantic-settings' __all__ minus the features fastenv omits, so that a one-line import swap would work. I should have checked that before trimming.
The migration note is the first sentence under "Coming from pydantic-settings" in docs/settings.md. It is the only place the docs promise a drop-in import. My commit a7debfd changed it like this:
−Already using pydantic-settings? Change `from pydantic_settings import ...` to `from fastenv import ...`, and keep importing everything else from `pydantic`.+Already using pydantic-settings? `BaseSettings`, `SettingsConfigDict`, and `SettingsError` come from `fastenv`. Source classes, `NoDecode`, and `ForceDecode` come from `fastenv.settings.pydantic_settings_sources`. Everything else still comes from `pydantic`.The old sentence was a drop-in promise; the new one makes migrating users split their imports across two modules.The evidence for your hypothesis. pydantic_settings.__all__ in 2.16.2 has 35 names:
- 14 are CLI names (
CliApp,CliSettingsSource,get_subcommand, and so on). - 4 are cloud sources (two AWS, Azure, Google).
- 1 is
YamlConfigSettingsSource. - 1 is
__version__. - The remaining 15 are exactly the 15 names the root exported before my trim.
The commit that added them, 349f193 "Expose Pydantic settings from the root package", does not state this reason, so the intent is my inference from the exact match and the old migration sentence.
What the trim cost. Before, from pydantic_settings import BaseSettings, TomlConfigSettingsSource, NoDecode became from fastenv import ... unchanged. Now anyone who customizes sources or uses NoDecode/ForceDecode must also import from fastenv.settings.pydantic_settings_sources.
My original argument for trimming was house style: the root had eight exports before this PR, and StarletteConfig is the only one for Starlette. That argument does not outweigh a documented drop-in import, so I recommend reverting a7debfd: restore the 15 exports, the old migration sentence, and the other three docs edits.
If you would still like something from the trim, the one-line .dotenv import is independent of this and can stay.
Should I revert the trim?
The trim is reverted in 92254bb, and the one-line .dotenv import is kept. CI is running.
Compared with the state before the trim, the only difference is that import line in fastenv/init.py. The 15 root exports, the four docs edits in docs/settings.md (including the migration note), and both tests are back as they were.
Local checks: 268 tests pass, the root and settings files are at 100% coverage, and ruff, prettier, and basedpyright are clean.
Decision to veto: I added a revert commit instead of dropping a7debfd from the branch, so the commit links earlier in this thread still resolve. The trim and its revert are both in the branch history.
The PR description needed no change. The last open review point is logging in the Pydantic sources.
CI passed for 92254bb: the tests on Python 3.11 to 3.14, CodeQL, and Vercel all succeeded (pypi and changelog were skipped). No action needed.
The last open review point is logging in the Pydantic sources.
The Pydantic settings sources now log a fastenv loaded N variables from <path> line at INFO on the "fastenv" logger for each dotenv, JSON, TOML, or pyproject file they read. It is pushed as 2319e5a, and CI is running. This was the last open review point.
A real run with a missing .env.local configured:
INFO:fastenv:fastenv loaded 3 variables from .env
INFO:fastenv:fastenv loaded 1 variables from service.toml
Correction to my review: I said starlette_config.py logs every load. It logs only errors. Only dotenv.py logs successes, so that is the pattern I matched.
Verification
- Tests:
hatch run coverage run -m pytest -q -p no:cacheprovider --ignore=tests/cloudgave 270 passed, with the settings modules still at 100% coverage. The two new tests fail without the source change. - Types and lint: basedpyright reports 0 errors and 0 warnings. Ruff and Prettier pass.
- CodeQL: a local run of the
python-code-scanningsuite reports 0 results.
Decisions you may want to veto
- Secret directories are not logged. My review asked for this, but a per-directory line raised two
py/clear-text-logging-sensitive-dataalerts in local CodeQL. They were false positives (only a count and a path were logged), but they would show up in your CodeQL check. The docs say secret files aren't logged. - No ERROR lines.
load_dotenvlogs errors becauseraise_exceptions=Falsecan swallow them. The Pydantic sources always raise, so an error line would only repeat the exception. - One line per file, not per source. Missing files are skipped silently, so the log shows which configured files were actually found.
- "variables" for JSON and TOML too. The count is the top-level keys of the document, or of the selected TOML table. I kept one wording so the line greps the same everywhere; "1 variables" is unpluralized, as in
load_dotenv. - Lines repeat on every
Settings()construction, the same as everyload_dotenvcall. - Test style follows
tests/test_dotenv.py:mocker.patch.object(..., "logger", autospec=True)and assertions onlogger.info.tests/settings/test_starlette_config.pyusescaploginstead; say if you prefer that here. - Docs: one short paragraph and a sample line under "Sources and priority" in docs/settings.md, linking to "Exceptions and logging" in the dotenv docs.
raise SettingsError(f"Configuration file {path} must contain a mapping")+values = cast(dict[str, Any], values)+logger.info(f"fastenv loaded {len(values)} variables from {path}")if self._deep_merge:− data = deep_merge(data, cast(dict[str, Any], values))+ data = deep_merge(data, values)else:− data.update(cast(dict[str, Any], values))+ data.update(values)basedpyright warned that len(values) had a partially unknown type, so the document is now cast once here instead of once in each merge branch.I left the PR description unchanged; it makes no claims about logging.
CI passed for 2319e5a: the test jobs on Python 3.11 to 3.14, CodeQL, and the Vercel docs deployment all succeeded. The pypi and changelog jobs were skipped, as on earlier pushes.
No action is needed. All review points are now addressed on the PR branch.
Both logging tests now use caplog instead of a mocked logger, pushed as b2f6de2. CI is running.
The full suite gives 270 passed with the settings modules at 100% coverage, basedpyright reports 0 errors and 0 warnings, and Ruff passes. Both tests fail when I restore the source file from before the logging commit.
Decisions you may want to veto:
- Looser assertions, as in
test_starlette_config.py. The tests check that the count and path appear incaplog.text, that the missing file's path does not, and that every record is INFO. They no longer pin the whole message. caplog.set_level("INFO", logger="fastenv")in each test. The Starlette tests don't need it because they check ERROR records, which pytest captures by default. I passed the level as a string to avoid addingimport logging.- A new commit, not an amend.
2319e5awas already pushed and linked above, so I left it intact.
The mock-only imports (TYPE_CHECKING, MockerFixture, and the module import) are gone, so the test file's import block is back to what it was before the logging work. The PR description needed no change.
CI passed for b2f6de2: the test jobs on Python 3.11 to 3.14, CodeQL, and the Vercel docs deployment all succeeded. The pypi and changelog jobs were skipped, as on earlier pushes.
No action is needed. Every review point is now addressed on the PR branch.
PR #46 is mergeable again: I merged main into the branch as 2013fe7 and pushed it. The branch's files are unchanged from b2f6de2, and CI is running on the new commit.
Why it conflicted
The conflicts come from the squash merge, not the incident. PR #45 landed on main as one new commit, e3864ec. The 16 original Starlette commits under this branch are therefore not ancestors of main. Git compares the two from their last shared commit, 4923bd6, and sees the Starlette changes added on both sides. The seven files that both the Starlette and Pydantic work edit then conflict.
GitHub did retarget the PR base to main. It does not rebase the stacked branch, so this would have happened without the incident.
How I resolved it
The squash commit's tree is identical to 41695e5, the last Starlette commit, which this branch already contains. So main has nothing this branch lacks, and every conflict resolves to this branch's version. I used git merge -s ours origin/main, which records exactly that.
- Files unchanged:
git diff b2f6de2 HEADis empty, and the suite still gives 270 passed. - PR diff unchanged: 14 files, +4123 and -65 against
main, the same as it was against the Starlette branch. - GitHub state:
mergeableisMERGEABLE. The merge state isBLOCKEDwhile the checks run.
Decision you may want to veto
I merged instead of rebasing onto main. A merge matches the three "Merge updated Starlette ..." commits already in this branch, and it keeps every commit link in this thread valid. A rebase would rewrite all 47 commits and flatten those three merges.
On main, the ci run for e3864ec is still queued and CodeQL shows startup_failure. I did not touch those.
CI passed for the merge commit 2013fe7: the test jobs on Python 3.11 to 3.14, CodeQL, and the Vercel docs deployment all succeeded. The pypi and changelog jobs were skipped, as on earlier pushes.
No action is needed. PR #46 has no conflicts with main and its checks are green.