Foundational infrastructure for Foundry components.
Install mise (task runner and dev tool manager):
brew install miseOr follow the installation guide for other methods. Then activate mise in your shell profile.
FoundryContext is the single source of truth for all project-specific values. One call at
application startup makes everything available library-wide β logging, Sentry, database settings,
and more all derive from it automatically.
# main.py
from aignostics_foundry_core.foundry import FoundryContext, set_context
from aignostics_foundry_core.boot import boot
set_context(FoundryContext.from_package("myproject"))
boot()FoundryContext.from_package("myproject") reads package metadata and environment variables to
populate every field:
name,version,version_fullβ fromimportlib.metadataenvironmentβ resolved from env vars in priority order (see Configuration reference below)env_prefix("MYPROJECT_") β used by every settings class; all env vars for this project share this prefixis_container,is_cli,is_test,is_libraryβ detected automatically
boot() initialises logging (loguru), amends the SSL trust chain (truststore + certifi), and
optionally starts Sentry β all in one call.
Settings are loaded from the environment and from env files. Highest priority first:
.env.{environment}.env{MYPROJECT_ENV_FILE}(optional extra file; when the variable is set)~/.myproject/.env.{environment}~/.myproject/.env
from aignostics_foundry_core.foundry import get_context
ctx = get_context()
print(f"Running {ctx.name} v{ctx.version_full} in {ctx.environment}")
# β Running myproject v1.2.3+main-abc1234---run.12345---build.42 in stagingget_context() raises RuntimeError with a clear message if set_context() was never called.
Never call set_context() in tests. Pass a FoundryContext directly to functions via their
optional context parameter:
from aignostics_foundry_core.foundry import FoundryContext
from aignostics_foundry_core.log import logging_initialize
ctx = FoundryContext(name="myproject", version="0.0.0", version_full="0.0.0", environment="test")
logging_initialize(context=ctx)All public library functions (logging_initialize, sentry_initialize, boot, load_modules,
etc.) accept an optional context keyword argument and fall back to get_context() when it is
None.
All settings classes read from environment variables prefixed with {PREFIX} where
{PREFIX} = MYPROJECT_ for a package named myproject.
Read directly by FoundryContext.from_package() β no settings class.
| Variable | Default | Description |
|---|---|---|
{PREFIX}ENVIRONMENT |
"local" |
Deployment environment name. Highest priority. |
ENV |
β | Fallback environment (lower priority than {PREFIX}ENVIRONMENT). |
VERCEL_ENV |
β | Vercel deployment environment (lower priority). |
RAILWAY_ENVIRONMENT |
β | Railway deployment environment (lower priority). |
{PREFIX}RUNNING_IN_CONTAINER |
unset | Set to any non-empty value to mark is_container = True. |
{PREFIX}ENV_FILE |
unset | Path to an additional env file, inserted between the home-dir files and the local .env. |
Read by FoundryContext.from_package() to build version_full and version_with_vcs_ref. All
optional; most useful in CI.
| Variable | Default | Description |
|---|---|---|
VCS_REF |
read from .git/HEAD |
Branch name or commit SHA. Falls back to reading .git/HEAD when project path is found. |
COMMIT_SHA |
"unknown" |
Full commit SHA; first 7 chars used. |
BUILD_DATE |
"unknown" |
Build date string. |
CI_RUN_ID |
"unknown" |
CI system run ID. |
CI_RUN_NUMBER |
"unknown" |
CI system build number. |
BUILDER |
"uv" |
Build tool name. |
When any of these variables is set, version_full gains a +β¦ suffix, e.g.
1.2.3+main-abc1234---run.12345---build.42.
Settings class: LogSettings
| Variable | Default | Description |
|---|---|---|
{PREFIX}LOG_LEVEL |
INFO |
Log level: CRITICAL, ERROR, WARNING, SUCCESS, INFO, DEBUG, or TRACE. |
{PREFIX}LOG_STDERR_ENABLED |
true |
Enable logging to stderr. |
{PREFIX}LOG_FILE_ENABLED |
false |
Enable logging to a file. |
{PREFIX}LOG_FILE_NAME |
platform log dir | Path to the log file (validated on startup when FILE_ENABLED is true). |
{PREFIX}LOG_REDIRECT_LOGGING |
true |
Redirect stdlib logging to loguru via InterceptHandler. |
Settings class: SentrySettings. Sentry is only initialised when ENABLED=true and DSN is
set.
| Variable | Default | Description |
|---|---|---|
{PREFIX}SENTRY_ENABLED |
false |
Enable Sentry error and performance monitoring. |
{PREFIX}SENTRY_DSN |
unset | Sentry DSN (must be an HTTPS URL with a valid ingest.*.sentry.io domain). |
{PREFIX}SENTRY_DEBUG |
false |
Enable Sentry SDK debug mode. |
{PREFIX}SENTRY_SEND_DEFAULT_PII |
false |
Include personally-identifiable information in events. |
{PREFIX}SENTRY_MAX_BREADCRUMBS |
50 |
Maximum breadcrumbs stored per event. |
{PREFIX}SENTRY_SAMPLE_RATE |
1.0 |
Error event sample rate (0.0β1.0). |
{PREFIX}SENTRY_TRACES_SAMPLE_RATE |
0.1 |
Transaction/trace sample rate. |
{PREFIX}SENTRY_PROFILES_SAMPLE_RATE |
0.1 |
Profiler sample rate. |
{PREFIX}SENTRY_PROFILE_SESSION_SAMPLE_RATE |
0.1 |
Profile session sample rate. |
{PREFIX}SENTRY_PROFILE_LIFECYCLE |
"trace" |
Profile lifecycle mode: "trace" or "manual". |
{PREFIX}SENTRY_ENABLE_LOGS |
true |
Forward log records to Sentry. |
Settings class: OTelSettings. OpenTelemetry is only initialised when ENABLED=true and the
standard OTEL_EXPORTER_OTLP_ENDPOINT is set. Each signal is then independently toggleable β
traces and metrics default on, logs off (their volume/cost profile differs). Telemetry is exported
via OTLP/gRPC, e.g. to the internal OTel gateway backing the
Grafana stack (Tempo/Loki/Prometheus).
| Variable | Default | Description |
|---|---|---|
{PREFIX}OTEL_ENABLED |
false |
Master switch for OpenTelemetry export via OTLP. |
{PREFIX}OTEL_TRACES_ENABLED |
true |
Export traces (once ENABLED). |
{PREFIX}OTEL_METRICS_ENABLED |
true |
Export metrics (once ENABLED). |
{PREFIX}OTEL_LOGS_ENABLED |
false |
Bridge loguru records into OTLP log export (once ENABLED). |
Endpoint, service name, and all other exporter behaviour come from the standard, unprefixed OpenTelemetry environment variables the SDK reads itself β not project-prefixed settings:
| Variable | Default | Description |
|---|---|---|
OTEL_EXPORTER_OTLP_ENDPOINT |
unset | OTLP/gRPC collector endpoint. Required β export is skipped if unset. |
OTEL_SERVICE_NAME |
project name | Service name attached to all telemetry. Defaults to the FoundryContext name. |
OTEL_EXPORTER_OTLP_CERTIFICATE |
OS CA bundle, else certifi's | CA file for the exporter's TLS. The Foundry Cloud Run Dockerfile installs the fleet's internal CA into the OS trust store, so this defaults to that bundle (falls back to certifi's public-roots-only bundle if it isn't present, e.g. running locally); set explicitly to override. |
OTEL_RESOURCE_ATTRIBUTES |
unset | Extra resource attributes, comma-separated key=value pairs. |
OTEL_SEMCONV_STABILITY_OPT_IN |
http |
Opts HTTP instrumentation into the stable semantic conventions (low-cardinality route-template span names) instead of the old, experimental ones. |
Process-level tracing/metrics/logs are set up by boot(). boot() also applies default
auto-instrumentors (HTTPX, SQLAlchemy) when traces are enabled β override via
boot(otel_instrumentors=[...]), or pass [] to opt out. Request-level FastAPI spans are
instrumented automatically too: init_api() applies instrument_fastapi() to the app it builds
(and to every versioned sub-app) β no explicit call needed. A project that constructs its
FastAPI instance some other way can call instrument_fastapi(app) directly, once, after
construction.
Settings class: DatabaseSettings. Database configuration is only activated when {PREFIX}DB_URL
is present (in the environment or in an env file).
| Variable | Required | Default | Description |
|---|---|---|---|
{PREFIX}DB_URL |
to activate | β | Full async database connection URL (e.g. postgresql+asyncpg://user:pass@host/db). Always access via DatabaseSettings.get_url(). |
{PREFIX}DB_POOL_SIZE |
no | 10 |
SQLAlchemy connection pool size. |
{PREFIX}DB_POOL_MAX_OVERFLOW |
no | 10 |
Max connections above pool size. |
{PREFIX}DB_POOL_TIMEOUT |
no | 30.0 |
Seconds to wait for a pool connection. |
{PREFIX}DB_NAME |
no | unset | Override the database name in the URL path at runtime. |
Once a context is configured via set_context(), all database functions work with no arguments β
the URL and pool settings are read from the context:
from aignostics_foundry_core.database import init_engine, cli_run_with_db, with_engine
# Zero-arg engine init β reads MYPROJECT_DB_URL, _DB_POOL_SIZE, etc. from env
init_engine()
# CLI helper β initialises engine, runs coroutine, disposes engine
cli_run_with_db(my_async_func)
# Background job decorator β engine initialised before each invocation
@with_engine
async def my_job(): ...
# Override for a secondary database
@with_engine(db_url="postgresql+asyncpg://user:pass@host/secondary")
async def my_other_job(): ...In tests, construct DatabaseSettings directly instead of setting env vars:
from aignostics_foundry_core.database import DatabaseSettings
from tests.conftest import make_context
ctx = make_context(database=DatabaseSettings(_env_prefix="TEST_DB_", url="sqlite+aiosqlite:///test.db"))Settings class: AuthSettings. All fields are optional with defaults unless enabled=True, which
activates several cross-field requirements. Only needed when using
aignostics_foundry_core.api.auth dependencies.
| Variable | Required | Default | Description |
|---|---|---|---|
{PREFIX}AUTH_ENABLED |
no | false |
Enable Auth0 authentication. When true, several other fields become required. |
{PREFIX}AUTH_SESSION_SECRET |
when enabled | "" |
Secret to sign session cookies. Required when AUTH_ENABLED=true. |
{PREFIX}AUTH_SESSION_EXPIRATION |
no | 86400 |
Session cookie expiration in seconds (range: 61β31536000). |
{PREFIX}AUTH_DOMAIN |
when enabled | "" |
Auth0 domain (e.g. myapp.eu.auth0.com). Required when AUTH_ENABLED=true. |
{PREFIX}AUTH_CLIENT_ID |
when enabled | "" |
Auth0 client ID (max 32 chars). Required when AUTH_ENABLED=true. |
{PREFIX}AUTH_CLIENT_SECRET |
when enabled | "" |
Auth0 client secret (64 chars). Required when AUTH_ENABLED=true. |
{PREFIX}AUTH_INTERNAL_ORG_ID |
when enabled | "" |
Auth0 organization ID identifying the internal org (used by require_internal). Required when AUTH_ENABLED=true. |
{PREFIX}AUTH_ROLE_CLAIM |
when enabled | "" |
JWT claim name containing the user's role (e.g. https://myapp.example.com/roles). Required when AUTH_ENABLED=true. |
Read directly from the environment β no settings class.
| Variable | Default | Description |
|---|---|---|
{PREFIX}CONSOLE_WIDTH |
auto-detect | Override Rich console width (integer, characters). Defaults to terminal width or 80 in non-TTY environments. |
- Foundry Project Guide - Complete toolchain, testing, CI/CD, and project setup guide
- Security policy - Documentation of security checks, tools, and principles
- Release notes - Complete log of improvements and changes
- Attributions - Open source projects this project builds upon