Skip to content

API Reference parrot.scheduler.sanitize

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.scheduler.sanitize

View source

Input sanitization for values handed to APScheduler.

The scheduler receives loosely-typed values from two sources that are outside the type system's reach:

  • navconfig environment variables — CACHE_HOST / CACHE_PORT. navconfig's fallback= only applies when a key is absent; a key that is present-but-empty (CACHE_PORT= in a .env file) resolves to ''.
  • the navigator.service_scheduler table — schedule_type, backend and the free-form schedule_config JSONB column, all of which are written by API callers and hand-edited by operators.

Neither source guarantees a trimmed, non-empty, correctly-typed value, and APScheduler/redis-py fail late and opaquely when handed one. The production symptom that motivated this module::

apscheduler.scheduler(base.py:1162) :: Error getting due jobs from job
store 'redis': invalid literal for int() with base 10: ''

CACHE_PORT='' reached RedisJobStore(port=''). redis-py builds connections lazily, so int(port) did not run at construction — it ran on the first real command, which is get_due_jobs() inside APScheduler's job- processing loop. The result was a repeating error every scheduler tick with no pointer back to the misconfigured environment variable.

The helpers here apply a single, consistent policy at the boundary:

  • trim every string value;
  • filter blank strings and null-ish tokens ("", "none", "null", "nil", "undefined", "~", "-") down to "not provided";
  • coerce numeric values, range-checking them where APScheduler has a documented domain (ports, hours, minutes, days);
  • fall back to a safe documented default and emit a WARNING naming the offending field, or raise :class:SchedulerConfigError when no safe default exists.

.. important:: "Null if invalid" deliberately does not mean passing None through to a trigger. CronTrigger(hour=None, minute=None) is silently accepted by APScheduler and produces cron[] — a job that fires every minute. A blank cron field therefore falls back to its documented default (0), never to None.

Class SchedulerConfigError

Raised when a schedule's configuration cannot be made safe.

Used only where no defensible default exists — e.g. an interval schedule with no non-zero component, which APScheduler would silently turn into a one-second hot loop.

Function clean_bool

Coerce value to a bool, falling back to default.

clean_bool(value: Any, *, default: bool) -> bool

Parameter Type Default Description
value Any Raw value; a bool, or a token such as "yes" / "off".
default bool Returned when value is blank or unrecognized.

Returns: bool — The parsed boolean, or default.

Function clean_int

Coerce value to an int, falling back to default.

Accepts ints and numeric strings (" 6380 ", "6379.0"). Booleans are rejected: Python treats True as 1, which is never what a port or an hour field means. Values outside [minimum, maximum] fall back rather than propagating to APScheduler, which would raise late and opaquely.

clean_int(value: Any, *, default: Optional[int], minimum: Optional[int] = None, maximum: Optional[int] = None, field: Optional[str] = None) -> Optional[int]

Parameter Type Default Description
value Any Raw value from the environment or a JSONB column.
default Optional[int] Returned when value is unusable. May be None.
minimum Optional[int] None Inclusive lower bound, when the field has a domain.
maximum Optional[int] None Inclusive upper bound, when the field has a domain.
field Optional[str] None Field name used in the warning emitted on fallback.

Returns: Optional[int] — The coerced integer, or default.

Function clean_method_name

Return a public Python identifier or None.

clean_method_name(value: Any) -> Optional[str]

Parameter Type Default Description
value Any Raw method name supplied by an API caller.

Returns: Optional[str] — A trimmed method name, or None for a null-ish value.

Raises:

  • SchedulerConfigError — If the value is not a public Python identifier.

Function clean_misfire_grace_time

Return None or a non-negative number of seconds.

clean_misfire_grace_time(value: Any) -> Optional[int]

Parameter Type Default Description
value Any Raw API value. Null-ish values mean that the job always catches up after a missed fire.

Returns: Optional[int] — A non-negative integer number of seconds, or None.

Raises:

  • SchedulerConfigError — If the value is not a non-negative integer.

Function clean_str

Trim value and map blank/null-ish text to default.

clean_str(value: Any, *, default: Optional[str] = None, lower: bool = False, field: Optional[str] = None) -> Optional[str]

Parameter Type Default Description
value Any Raw value from the environment or a database column. Non-string values are coerced with str() before trimming.
default Optional[str] None Returned when value is None, blank, or a null token.
lower bool False Lowercase the result. Useful for enum-like fields.
field Optional[str] None Field name used in the warning emitted on fallback.

Returns: Optional[str] — The trimmed string, or default when nothing usable was supplied.

Function normalize_backend

Normalize a caller-supplied backend to 'db' or 'redis'.

normalize_backend(value: Any, *, redis_available: bool, strict: bool = False) -> str

Parameter Type Default Description
value Any Raw backend value supplied by an API caller or database row.
redis_available bool Whether a Redis jobstore is attached to the scheduler.
strict bool False Raise instead of falling back to 'db' for unavailable Redis.

Returns: str — The normalized backend name.

Raises:

  • SchedulerConfigError — If the backend is unknown, or Redis is requested strictly when no Redis jobstore is attached.

Function normalize_schedule_type

Trim, lowercase and validate a schedule_type.

normalize_schedule_type(value: Any) -> str

Parameter Type Default Description
value Any Raw schedule_type value.

Returns: str — The canonical lowercase schedule type.

Raises:

  • SchedulerConfigError — When blank or not a supported type. A schedule with no type cannot be defaulted — there is no safe guess between "run once" and "run every minute".

Function sanitize_redis_settings

Build validated connection settings for RedisJobStore.

This is the direct fix for the reported production failure: redis-py defers int(port) to the first connection, so an empty CACHE_PORT only surfaces once APScheduler polls for due jobs.

sanitize_redis_settings(host: Any, port: Any, db: Any = DEFAULT_REDIS_JOBSTORE_DB) -> Dict[str, Any]

Parameter Type Default Description
host Any Raw CACHE_HOST value.
port Any Raw CACHE_PORT value.
db Any DEFAULT_REDIS_JOBSTORE_DB Raw Redis database index for the jobstore.

Returns: Dict[str, Any] — Mapping with host (str), port (int) and db (int), ready to splat into RedisJobStore(...).

Function sanitize_schedule_config

Trim, filter and coerce a schedule_config for its schedule type.

The single entry point used by the scheduler before building a trigger. Blank and null-ish values are replaced by the documented default for the field; unknown keys are dropped; numeric fields are coerced and range-checked. Configurations with no safe interpretation raise :class:SchedulerConfigError, so the offending schedule is skipped with a clear message instead of misfiring.

sanitize_schedule_config(schedule_type: Any, config: Optional[Dict[str, Any]]) -> Dict[str, Any]

Parameter Type Default Description
schedule_type Any Raw schedule type; normalized internally.
config Optional[Dict[str, Any]] Raw schedule_config JSONB payload. None is treated as an empty mapping.

Returns: Dict[str, Any] — A mapping safe to hand to the matching APScheduler trigger.

Raises:

  • SchedulerConfigError — When the type is unsupported or the config cannot be made safe.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally