def test_cache_page_with_missing_events(temp_dir: str):
    """Test cache behavior when some events are missing."""
    file_store = get_file_store('local', temp_dir)

    # Create an event stream with a small cache size
    event_stream = EventStream('missing_test', file_store)
    event_stream.cache_size = 5

    # Add events
    for i in range(10):
        event_stream.add_event(NullObservation(f'test{i}'), EventSource.AGENT)

    # Create a new event stream to force reloading events
    new_stream = EventStream('missing_test', file_store)
    new_stream.cache_size = 5

    # Get the initial count of events
    initial_events = list(new_stream.get_events())
    initial_count = len(initial_events)

    # Delete an event file to simulate a missing event
    # Choose an ID that's not at the beginning or end
    missing_id = 5
    missing_filename = new_stream._get_filename_for_id(missing_id, new_stream.user_id)
    try:
        file_store.delete(missing_filename)

        # Create another stream to force reloading after deletion
        reload_stream = EventStream('missing_test', file_store)
        reload_stream.cache_size = 5

        # Retrieve events after deletion
        events_after_deletion = list(reload_stream.get_events())

        # We should have fewer events than before
        assert len(events_after_deletion) <= initial_count, (
            'Should have fewer or equal events after deletion'
        )

        # Test that we can still retrieve events successfully
        assert len(events_after_deletion) > 0, 'Should still retrieve some events'

    except Exception as e:
        # If the delete operation fails, we'll just verify that the basic functionality works
        print(f'Note: Could not delete file {missing_filename}: {e}')
        assert len(initial_events) > 0, 'Should retrieve events successfully'
Test cache behavior when some events are missing.
tests/unit/test_event_stream.py