-
Notifications
You must be signed in to change notification settings - Fork 0
feat: consolidate env-var readers on common/env_config (RES-1297) #188
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
KarinaKKarinaK
wants to merge
3
commits into
main
Choose a base branch
from
karinakalicka/res-1297-consolidate-env-var-readers-on-commonenv_config-in
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
06f0fac
feat(common): add shared env_config reader (RES-1297)
KarinaKKarinaK 95724fc
refactor: retire private env readers, route through common.env_config…
KarinaKKarinaK ea22cda
fix: preserve empty-var warning, bound the LLM knobs, assert warnings…
KarinaKKarinaK File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """Single contract for reading validated env-var overrides. | ||
|
|
||
| One place the package parses and validates environment overrides, so a tuning knob behaves the | ||
| same wherever it is read. The contract: | ||
|
|
||
| - unset (variable absent) -> the default, silently. | ||
| - a set-but-invalid value logs a WARNING and falls back to the default. It never raises, so a | ||
| misconfigured knob is actionable but non-fatal. "Invalid" for a number means: empty/whitespace | ||
| (in a CI ``env:`` block an unresolved ``${{ vars.X }}`` expands to empty, which should be a | ||
| signal, not a silent default), unparseable, or outside an optional ``[min_value, max_value]`` | ||
| range. For a bool, empty is treated as unset (-> default). | ||
|
|
||
| Prefer ``env_int`` / ``env_float`` / ``env_bool`` over ad hoc ``os.getenv`` + ``int()`` / ``float()`` | ||
| in the package. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import math | ||
| import os | ||
|
|
||
| from loguru import logger | ||
|
|
||
| _TRUE = {'1', 'true', 'yes', 'on'} | ||
| _FALSE = {'0', 'false', 'no', 'off'} | ||
|
|
||
|
|
||
| def _bounded(name: str, value: float, default: float, min_value: float | None, max_value: float | None) -> float: | ||
| if min_value is not None and value < min_value: | ||
| logger.warning('{} must be >= {} (got {}); using default {}.', name, min_value, value, default) | ||
| return default | ||
| if max_value is not None and value > max_value: | ||
| logger.warning('{} must be <= {} (got {}); using default {}.', name, max_value, value, default) | ||
| return default | ||
| return value | ||
|
|
||
|
|
||
| def _raw_number(name: str, default: float) -> str | None: | ||
| """Shared prelude for env_int/env_float: None if unset (silent), else the stripped value; | ||
| an empty/whitespace value warns and returns None so the caller falls back to the default.""" | ||
| raw = os.environ.get(name) | ||
| if raw is None: | ||
| return None | ||
| raw = raw.strip() | ||
| if not raw: | ||
| logger.warning('{} is set but empty; using default {}.', name, default) | ||
| return None | ||
| return raw | ||
|
|
||
|
|
||
| def env_int(name: str, default: int, *, min_value: int | None = None, max_value: int | None = None) -> int: | ||
| """Read an int override. Unset -> default; empty/invalid/out-of-range -> WARNING + default.""" | ||
| raw = _raw_number(name, default) | ||
| if raw is None: | ||
| return default | ||
| try: | ||
| value = int(raw) | ||
| except ValueError: | ||
| logger.warning('{} is not an integer ({!r}); using default {}.', name, raw, default) | ||
| return default | ||
| return int(_bounded(name, value, default, min_value, max_value)) | ||
|
|
||
|
|
||
| def env_float(name: str, default: float, *, min_value: float | None = None, max_value: float | None = None) -> float: | ||
| """Read a float override. Unset -> default; empty/invalid/out-of-range -> WARNING + default.""" | ||
| raw = _raw_number(name, default) | ||
| if raw is None: | ||
| return default | ||
| try: | ||
| value = float(raw) | ||
| except ValueError: | ||
| logger.warning('{} is not a number ({!r}); using default {}.', name, raw, default) | ||
| return default | ||
| if not math.isfinite(value): # float() accepts nan/inf; a knob is never one of those | ||
| logger.warning('{} is not a finite number ({!r}); using default {}.', name, raw, default) | ||
| return default | ||
| return float(_bounded(name, value, default, min_value, max_value)) | ||
|
|
||
|
|
||
| def env_bool(name: str, *, default: bool) -> bool: | ||
| """Read a bool override. Unset/empty -> default; unrecognised -> WARNING + default. | ||
|
|
||
| Truthy: 1/true/yes/on. Falsy: 0/false/no/off (case-insensitive). | ||
| """ | ||
| raw = os.environ.get(name) | ||
| if raw is None or raw == '': | ||
| return default | ||
| value = raw.strip().lower() | ||
| if value in _TRUE: | ||
| return True | ||
| if value in _FALSE: | ||
| return False | ||
| logger.warning('{} is not a boolean ({!r}); using default {}.', name, raw, default) | ||
| return default | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| """Tests for the shared env-var reader contract (common/env_config). | ||
|
|
||
| Covers the return value AND that a WARNING is actually emitted on every invalid case, since a | ||
| silent misconfiguration is the failure this reader exists to prevent. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| import pytest | ||
| from loguru import logger | ||
|
|
||
| from evaluatorq.common.env_config import env_bool, env_float, env_int | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Iterator | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def _clear(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| for name in ('X_INT', 'X_FLOAT', 'X_BOOL'): | ||
| monkeypatch.delenv(name, raising=False) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def warns() -> Iterator[list[str]]: | ||
| """Capture loguru WARNING messages (loguru does not feed pytest's caplog).""" | ||
| messages: list[str] = [] | ||
| sink_id = logger.add(lambda m: messages.append(m.record['message']), level='WARNING') | ||
| yield messages | ||
| logger.remove(sink_id) | ||
|
|
||
|
|
||
| # --- env_int --- | ||
| def test_env_int_unset_is_silent(warns: list[str]) -> None: | ||
| assert env_int('X_INT', 7) == 7 | ||
| assert warns == [] # a truly-absent variable is not a misconfiguration | ||
|
|
||
|
|
||
| def test_env_int_empty_warns(monkeypatch: pytest.MonkeyPatch, warns: list[str]) -> None: | ||
| monkeypatch.setenv('X_INT', '') | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This pins the silent-empty behaviour as intended, which is the opposite of what CHANGELOG.md:20 claims for this contract. Once empty warns, split this into an unset case and an empty case that asserts the warning. |
||
| assert env_int('X_INT', 7) == 7 | ||
| assert any('set but empty' in m for m in warns) # unresolved CI ${{ vars.X }} must signal | ||
|
|
||
|
|
||
| def test_env_int_whitespace_only_warns(monkeypatch: pytest.MonkeyPatch, warns: list[str]) -> None: | ||
| monkeypatch.setenv('X_INT', ' ') | ||
| assert env_int('X_INT', 7) == 7 | ||
| assert any('set but empty' in m for m in warns) | ||
|
|
||
|
|
||
| def test_env_int_valid_and_stripped(monkeypatch: pytest.MonkeyPatch, warns: list[str]) -> None: | ||
| monkeypatch.setenv('X_INT', '42') | ||
| assert env_int('X_INT', 7) == 42 | ||
| monkeypatch.setenv('X_INT', ' 42 ') # surrounding whitespace tolerated | ||
| assert env_int('X_INT', 7) == 42 | ||
| assert warns == [] # a valid value warns about nothing | ||
|
|
||
|
|
||
| def test_env_int_invalid_warns_and_defaults(monkeypatch: pytest.MonkeyPatch, warns: list[str]) -> None: | ||
| monkeypatch.setenv('X_INT', 'notanint') | ||
| assert env_int('X_INT', 7) == 7 # never raises | ||
| assert any('not an integer' in m for m in warns) | ||
|
|
||
|
|
||
| def test_env_int_out_of_range_warns_and_defaults(monkeypatch: pytest.MonkeyPatch, warns: list[str]) -> None: | ||
| monkeypatch.setenv('X_INT', '0') | ||
| assert env_int('X_INT', 7, min_value=1) == 7 # replaces the old "must be positive" check | ||
| monkeypatch.setenv('X_INT', '999') | ||
| assert env_int('X_INT', 7, max_value=100) == 7 | ||
| assert sum('must be' in m for m in warns) == 2 | ||
|
|
||
|
|
||
| # --- env_float --- | ||
| def test_env_float_valid_invalid_range(monkeypatch: pytest.MonkeyPatch, warns: list[str]) -> None: | ||
| monkeypatch.setenv('X_FLOAT', '1.5') | ||
| assert env_float('X_FLOAT', 2.0) == 1.5 | ||
| monkeypatch.setenv('X_FLOAT', 'nope') | ||
| assert env_float('X_FLOAT', 2.0) == 2.0 | ||
| monkeypatch.setenv('X_FLOAT', '-1') | ||
| assert env_float('X_FLOAT', 2.0, min_value=0.0) == 2.0 | ||
| assert any('not a number' in m for m in warns) | ||
| assert any('must be >=' in m for m in warns) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize('raw', ['nan', 'inf', '-inf', 'Infinity']) | ||
| def test_env_float_rejects_non_finite(monkeypatch: pytest.MonkeyPatch, warns: list[str], raw: str) -> None: | ||
| monkeypatch.setenv('X_FLOAT', raw) | ||
| assert env_float('X_FLOAT', 2.0) == 2.0 # float() would accept these; the reader must not | ||
| assert any('finite' in m for m in warns) | ||
|
|
||
|
|
||
| # --- env_bool --- | ||
| @pytest.mark.parametrize(('raw', 'expected'), [('1', True), ('true', True), ('YES', True), ('on', True), ('0', False), ('false', False), ('no', False), ('OFF', False)]) | ||
| def test_env_bool_recognised(monkeypatch: pytest.MonkeyPatch, raw: str, expected: bool) -> None: | ||
| monkeypatch.setenv('X_BOOL', raw) | ||
| assert env_bool('X_BOOL', default=not expected) is expected | ||
|
|
||
|
|
||
| def test_env_bool_unset_is_silent(warns: list[str]) -> None: | ||
| assert env_bool('X_BOOL', default=True) is True | ||
| assert warns == [] | ||
|
|
||
|
|
||
| def test_env_bool_unrecognised_warns_and_defaults(monkeypatch: pytest.MonkeyPatch, warns: list[str]) -> None: | ||
| monkeypatch.setenv('X_BOOL', 'maybe') | ||
| assert env_bool('X_BOOL', default=True) is True # unrecognised -> warn + default, never raises | ||
| assert any('not a boolean' in m for m in warns) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2 — this tests for empty before it strips, so a whitespace-only value warns
is not a boolean._raw_numberstrips first and warnsis set but emptyfor the same input. Strip here too.