schedule_schema module is the validation layer for the tif1 internal schedule data architecture. It checks the structure of the vendored schedule data before the schedule APIs read it, and it can check custom schedule payloads too.
Purpose and Role
The schedule validation system checks that a schedule payload conforms to the tif1 internal schema before higher-level APIs use it. This applies to the vendored JSON files and to custom data passed to the validator. Years fetched from the f1schedule repository only pass the conversion checks. This validation layer provides these functions:- Data Integrity Assurance: Validates that schedule data structures are complete, correctly typed, and internally consistent
- Early Error Detection: Catches malformed or incomplete data at the earliest possible stage, preventing cascading failures
- Schema Version Management: Ensures compatibility between data format versions and library expectations
- Type Safety Enforcement: Verifies that all data elements match their expected types throughout the hierarchy
- Consistency Guarantees: Ensures a uniform data structure across all vendored years and events
For Most Users: This module operates transparently. Schedule data is accessed through high-level APIs like
get_events(), get_sessions(), and get_event_schedule(), which handle validation automatically. Direct use is needed only for advanced scenarios: custom schedule data, debugging, or extending the library.Architecture Overview
Data Flow Pipeline
The schedule validation system sits at a critical junction in tif1’s data pipeline. Understanding this flow helps clarify when and why validation occurs:Key Design Principles
- Fail-Fast Philosophy: Validation of the vendored files occurs immediately after data conversion, before any caching or API exposure. This ensures that invalid data never propagates through the system.
- Single Validation Point: The vendored schedule data passes through one validation function. Years fetched from the f1schedule repository only pass the conversion checks.
- Performance Optimization: Validation is fast (typically <1ms) and runs only once per process due to caching.
- Detailed Error Reporting: When validation fails, the system provides specific error messages that identify what went wrong and where.
-
Type Safety: The validation system checks the type of each level it covers: payload, years, events, and session lists. It does not check
metadata.
Validation Scope
The validation system checks multiple aspects of schedule data:Performance Characteristics
The validation system is optimized for production use:- Time Complexity: Linear in the total number of events and session names
- Typical Runtime: <1ms for standard multi-year schedules (5-10 years)
- Memory Overhead: Minimal; validates in-place without copying data structures
- Caching Strategy: Results cached via
@lru_cache; validation runs once per Python session - Scalability: Handles schedules with 20+ events per year efficiently
Measured: The full vendored payload (9 seasons, 205 events) validates in about 0.05 ms; one season takes about 0.01 ms.
Core API Reference
validate_schedule_payload
Function Signature
Parameters:payload(Any): The decoded schedule payload to validate. While typed asAnyto accept arbitrary input, the function expects a dictionary with the following structure:
dict[str, Any]: The validated payload, returned unchanged if all validation checks pass. This design allows for method chaining and confirms that the payload is safe for use in downstream operations. The return value is guaranteed to match the expected schema structure.
InvalidDataError: Raised when any validation check fails. The exception includes:message: Human-readable description of the validation failure (Invalid data: <reason>)context: Dictionary with a single key,reason, naming the violated rule (e.context["reason"])
Validation Process
The function performs validation in a hierarchical, top-down manner. It checks each level of the data structure before it proceeds to the next:Level 1: Top-Level Structure Validation
Level 2: Schema Version Validation
Level 3: Years Container Validation
Level 4: Per-Year Structure Validation
Level 5: Session Mapping Validation
Usage Examples
Example 1: Basic Validation (Success Case)
Example 2: Handling Validation Errors
Example 3: Multi-Year Validation
Example 4: Validating Sprint Weekend Format
Example 5: Validation with Metadata (Optional Fields)
Example 6: Error Recovery Pattern
Common Validation Failures
Here is a reference of common validation failures and how to fix them:Performance Considerations
The validation function is optimized for production use:- Fast Execution: Validating the full vendored payload (9 seasons) takes about 0.05 ms
- No Data Copying: Validates in-place without creating copies of the data structure
- Early Exit: Stops at the first validation failure, avoiding unnecessary checks
- Minimal Allocations: Uses efficient iteration patterns to minimize memory allocations
Schedule Schema Specification
Schema Structure
The internal schedule schema is event-centric. It is optimized for the most common query patterns in Formula 1 data analysis. This structure differs from the raw f1schedule format, which uses a columnar layout. The event-centric structure gives better performance for event and session lookups.Complete Schema Definition
Real-World Example: 2021 Belgian Grand Prix
This excerpt of the converted 2021 payload has the fullevents list but the sessions and metadata of one event only.
Field Specifications
Top-Level Fields
Year Payload Fields
Event Metadata Fields
The f1schedule files carry no UTC columns. The conversion (
_convert_f1schedule_year(), used for vendored and fetched files alike) computes each SessionNDateUtc as the local SessionNDate minus GmtOffset. When GmtOffset is missing or cannot be parsed, the Utc fields are left out, and the Event holds NaT for them.Session Name Standards
Session names follow standardized conventions:Standard Session Names
Sprint Weekend Session Names
Sprint weekends have a different structure:Sprint Format Evolution: The scheduled sessions of a sprint weekend changed over the years:
- 2021-2022 (
EventFormat“sprint”): Practice 1, Qualifying, Practice 2, Sprint, Race - 2023 (“sprint_shootout”): Practice 1, Qualifying, Sprint Shootout, Sprint, Race
- 2024 onward (“sprint_qualifying”): Practice 1, Sprint Qualifying, Sprint, Qualifying, Race
Event.get_session_name() maps “Sprint Qualifying” to “Sprint” for backward compatibility.Event Format Types
TheEventFormat metadata field indicates the weekend structure:
Schema Version History
Version 1 (Current)
- Status: Current and only supported version
- Features:
- Event-centric structure
- Support for conventional, sprint, and testing formats
- Metadata with timezone information
- Session dates in local time and in UTC
Validation Rules Reference
This section provides a reference of all validation rules enforced byvalidate_schedule_payload().
Rule Categories
Category 1: Structural Validation
These rules ensure the payload has the correct overall structure:Category 2: Year-Level Validation
These rules validate each year entry in theyears dictionary:
Category 3: Session-Level Validation
These rules validate session mappings for each event:Validation Order
The validation process follows this exact order:Early Exit Behavior: Validation stops at the first rule violation. Only one error is reported at a time, even if multiple issues exist. Fix the reported error and re-validate to discover any additional issues.
Common Validation Scenarios
Scenario 1: Empty Payload
Scenario 2: Wrong Data Type
Scenario 3: Invalid Year Key
Scenario 4: Missing Session Mapping
Scenario 5: Empty Session List
Empty Lists: Empty event lists and empty session lists pass validation. For an event with an empty session list,
get_sessions() returns the conventional five-session list. The validation layer checks structural correctness only, not business logic constraints.Scenario 6: Invalid Session Type
Validation Best Practices
1. Validate Early
Always validate immediately after constructing or loading schedule data:2. Provide Context in Errors
When wrapping validation, preserve error context:3. Build Payloads Incrementally
When constructing complex payloads, validate at each stage:4. Handle Validation in Pipelines
For data processing pipelines, use validation as a quality gate:Error Handling
Exception Hierarchy
Schedule validation errors are part of tif1’s exception hierarchy:InvalidDataError Structure
When validation fails, anInvalidDataError is raised with the following structure:
message(str): Human-readable error messagecontext(dict[str, Any]): Structured error context containing:reason(str): Detailed explanation of the validation failurevalidate_schedule_payload()sets no other context keys
Error Message Patterns
All validation error messages follow consistent patterns:Catching and Handling Errors
Basic Error Handling
Detailed Error Inspection
Error Recovery Strategies
Logging Validation Errors
Custom Error Messages
Debugging Validation Failures
Strategy 1: Incremental Validation
Build and validate the payload incrementally to isolate issues:Strategy 2: Payload Inspection
Inspect the payload structure before validation:Common Error Scenarios and Solutions
Integration with tif1
How Validation Fits into tif1’s Architecture
The schedule validation system is a foundational component that enables reliable operation of all schedule-related APIs in tif1. The integration works as follows:Internal Usage Flow
Public APIs That Use Validation
For a past season served from the vendored files, every schedule API reads the validated payload. A live season (the current or a future year) goes through the conversion checks instead; see Data Source Priority. The flows below show the vendored path:get_events(year)
Returns an EventSchedule DataFrame for a given year (the same as get_event_schedule(year)).
get_sessions(year, event)
Returns a list of session names for a specific event. A name that is not an exact EventName resolves like get_event_by_name() (alias table, then fuzzy matching). A fuzzy match needs a score of at least 70 (rapidfuzz ratio, 0-100). A name that matches no event raises EventNotFoundError (a ValueError). An alias of an event that is not on that calendar raises EventNotInSeasonError, its subclass.
get_event_schedule(year)
Returns a pandas DataFrame with the complete event schedule for a year.
get_event(year, identifier)
Returns an Event object for a specific event. A name that matches no event gives None instead of an exception. get_event_by_name() raises EventNotFoundError for the same name.
Data Source Priority
The source depends on whether the season can still change:validate_schedule_payload(). A fetched year only goes through the conversion, which raises InvalidDataError for a malformed file. tif1 logs that error and continues down the fallback chain. A failed fetch logs a warning and falls back to the stale row or the vendored file, so the current season is still resolvable offline.
Caching Strategy
Validation results are cached to minimize overhead:- Vendored Data: Validated once per Python session, cached indefinitely
- Live Data: The raw upstream file is cached in SQLite for
schedule_ttl_hours(default 6,TIF1_SCHEDULE_TTL_HOURS) and memoized in the process for the same window. A failed fetch keeps the fallback for 5 minutes before the next attempt - Performance Impact: The first call reads and converts all vendored files (a few milliseconds). Later calls are cache hits
Custom Schedule Data Integration
Integrate custom schedule data with the tif1 validation system:Example: Loading Custom Schedule File
Example: Building Schedule Programmatically
Example: Extending Vendored Schedule
Testing with Validation
When writing tests for schedule-related code, use validation to ensure test data quality:Advanced Topics
Raw f1schedule Format vs Internal Format
tif1 uses two different data formats internally:Raw f1schedule Format (Columnar)
The vendored JSON files use a columnar format similar to pandas DataFrames:- Structure: Column-oriented (each field is a dictionary mapping indices to values)
- Efficiency: Compact storage, easy to convert to/from pandas DataFrames
- Query Pattern: Requires iteration to find specific events
- Source: f1schedule repository (https://github.com/theOehrly/f1schedule)
Internal Format (Event-Centric)
After conversion and validation, tif1 uses an event-centric format:- Structure: Event-oriented (each event is a top-level entity)
- Efficiency: Fast event and session lookups (O(1) dictionary access)
- Query Pattern: Direct access by event name
- Source: Converted from raw format by
_convert_f1schedule_year()
Conversion Process
The conversion from raw to internal format happens in_convert_f1schedule_year():
- Raw Format: The format of the upstream f1schedule repository, the files FastF1 reads. Vendored and fetched files share it, so one converter handles both
- Internal Format: Optimized for runtime queries (faster lookups, better API ergonomics)
Performance Optimization Techniques
Technique 1: Lazy Loading
Schedule data is loaded only when first accessed:Technique 2: Immutable Caching
Event and session lists are cached as immutable tuples:- Immutability prevents accidental modification of the memo
get_events()andget_sessions()return new objects built from the tuples, so a caller that changes them does not change the memo
Technique 3: Validation Short-Circuiting
Validation stops at the first error:- Faster failure for invalid data
- Reduces unnecessary computation
- Provides immediate feedback
Technique 4: In-Place Validation
Validation does not copy data:- Zero memory overhead
- Faster validation (no allocation/copying)
- Suitable for large schedules
Extending the Validation System
Adding Custom Validation Rules
Wrap the built-in validation with additional checks:Creating Validation Decorators
Wrap functions with validation:Building Validation Pipelines
Chain multiple validation steps:Troubleshooting Guide
Issue: Validation Passes But API Fails
Symptom:validate_schedule_payload() succeeds, but events in get_event_schedule() have no country, no dates, or a guessed location.
Cause: Metadata might be missing or malformed (not validated by schema validator).
Solution:
Issue: Performance Degradation
Symptom: Validation becomes slow with large schedules. Cause: Validation time grows linearly with the total number of events and session names. Solution:Issue: Cryptic Error Messages
Symptom: Error message does not clearly indicate the problem. Cause: Complex nested structure makes errors hard to pinpoint. Solution:Complete Working Examples
Example 1: Basic Schedule Validation
Example 2: Loading and Validating from JSON File
Example 3: Building Schedule Programmatically
Example 4: Validating Sprint Weekend Format
Example 5: Integration with tif1 APIs
Example 6: Error Handling and Recovery
Summary
Theschedule_schema module provides the foundational validation layer for tif1’s schedule data system. Key takeaways:
Core Concepts
- Single Validation Function:
validate_schedule_payload()is the only public API - Schema Version 1: The only supported version
- Event-Centric Structure: Internal format optimized for fast event/session lookups
- Fail-Fast Validation: Stops at first error with detailed error messages
- Performance Optimized: Typically <1ms validation time, cached results
When to Use
- Automatic: tif1 validates the vendored schedule files the first time a schedule API reads them
- Manual: When working with custom schedule data or building data pipelines
- Testing: To ensure test fixtures have valid structure
- Debugging: To diagnose schedule data issues
Best Practices
- Validate Early: Run validation immediately after loading or constructing schedule data
- Handle Errors: Always catch
InvalidDataErrorand provide user-friendly messages - Preserve Context: When wrapping validation, preserve error context for debugging
- Build Incrementally: For complex payloads, validate at each construction stage
- Validate Once: Cache a validated payload (for example with
functools.lru_cache), as tif1 does for the vendored files
Common Patterns
Related Documentation
For more information on working with schedule data in tif1:Events & Schedule API
High-level APIs for accessing event and session information.
Core Session API
Loading and working with session data.
Exception Handling
Complete exception hierarchy and error handling patterns.
Data Flow Concepts
Understanding tif1’s data pipeline architecture.
Quick Reference
Validation Rules Summary
Performance
Validating the full vendored payload (9 seasons, 205 events) takes about 0.05 ms. Reading and converting the vendored files, which happens once per process before that validation, takes a few milliseconds; later calls hit thelru_cache.
Schema Structure Quick Reference
Additional Resources
External Links
- f1schedule Repository: github.com/theOehrly/f1schedule - Source of raw schedule data
- tif1 GitHub: github.com/TracingInsights/tif1 - Main repository
- Issue Tracker: Report schedule validation issues on GitHub