cocoindex-io/cocoindex · error · ValueError

failed to parse environment variable {env_name}: {value}

Error message

failed to parse environment variable {env_name}: {value}

What it means

When an environment variable is present but fails its registered parse function (e.g. an int/bool/Dsn parser), _load_field wraps the parser exception in this ValueError so the offending variable name and raw value are visible. It means the value's format, not its presence, is wrong.

Source

Thrown at python/cocoindex/_internal/setting.py:53

def _load_field(
    target: dict[str, Any],
    name: str,
    env_name: str,
    required: bool = False,
    parse: Callable[[str], Any] | None = None,
) -> None:
    value = os.getenv(env_name)
    if value is None:
        if required:
            raise ValueError(f"{env_name} is not set")
    else:
        if parse is None:
            target[name] = value
        else:
            try:
                target[name] = parse(value)
            except Exception as e:
                raise ValueError(
                    f"failed to parse environment variable {env_name}: {value}"
                ) from e


@dataclass(init=False)
class Settings:
    """Settings for the cocoindex library."""

    db_path: os.PathLike[str] | None
    db_settings: LmdbSettings
    # Deprecated v0 leftover; has no effect in v1. Kept (always `None`) so callers
    # that still pass `global_execution_options=None` don't break.
    global_execution_options: None

    def __init__(
        self,
        db_path: os.PathLike[str] | None = None,
        db_settings: LmdbSettings | None = None,

View on GitHub (pinned to e84aa99b32)

Solutions

  1. Fix the env var value to match the expected format (e.g. plain integer bytes for size fields)
  2. Remove stray quotes, spaces, or trailing characters from the .env entry
  3. Test the value against the parse function implied by the field (int(), Dsn parsing, etc.)
  4. Check for shell interpolation issues that mangled the value

Example fix

// before
COCOINDEX_LMDB_MAP_SIZE="1gb"   # fails int parse
// after
COCOINDEX_LMDB_MAP_SIZE=1073741824
Defensive patterns

Strategy: validation

Validate before calling

raw = os.getenv("COCOINDEX_LMDB_MAP_SIZE", "")
if raw and not raw.strip().lstrip("+-").isdigit():
    raise SystemExit(f"COCOINDEX_LMDB_MAP_SIZE must be an int, got {raw!r}")

Try / catch

try:
    settings = Settings.from_env()
except ValueError as e:
    print(e)  # names the env var and offending value
    fix_env_and_retry()

Prevention

When it happens

Trigger: Calling from_env() where an env var exists but its value cannot be parsed — e.g. COCOINDEX_LMDB_MAP_SIZE="abc" for an int field, or a malformed URL/DSN passed to a DSN parser.

Common situations: Quoted or whitespace-polluted values in .env files ('123' with literal quotes); pasting values with trailing newlines; using non-numeric sizes for int settings; typos in URLs.

Understand the failure class

Background: "is not a valid" / "Invalid ... value" environment variable errors: how libraries validate env vars and what to do when they reject yours — this error's family across 48 libraries.

Related errors


AI-assisted analysis of cocoindex-io/cocoindex@e84aa99b32 (2026-09-08). Data as JSON: /api/errors/5bb876b1e556e749. Report an issue: GitHub.