Skip to content

Demo: aido docs - #69

Open
dvirdung wants to merge 1 commit into
mainfrom
demo/v132-docs
Open

Demo: aido docs#69
dvirdung wants to merge 1 commit into
mainfrom
demo/v132-docs

Conversation

@dvirdung

@dvirdung dvirdung commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Undocumented retry + LRU-ish cache helpers to showcase aido docs — drafting docstrings, parameters, and usage notes. Comment aido docs. Part of the Aido demo set.

@dvirdung dvirdung added the demo label Jul 21, 2026
@dvirdung

Copy link
Copy Markdown
Contributor Author

aido docs

@github-actions

Copy link
Copy Markdown

🤖 Hi @dvirdung, I’ve queued your aido docs request. Follow progress here: https://github.com/aido-dev/aido/actions/runs/29812286114

@github-actions

Copy link
Copy Markdown

📚 Aido Docs Draft

This pull request introduces two new utility helpers, a retry mechanism and an LRU-ish cache, located in the demo directory. These are provided primarily to showcase capabilities related to documentation generation but can also serve as foundational components for future features or internal tools.


demo/docs_demo.py Updates

This PR adds a new file, demo/docs_demo.py, which includes two general-purpose utilities: a retry function for robust operation execution and a Cache class for in-memory caching. These components are currently located in the demo directory, indicating their experimental or demonstration status.

Usage and Purpose

These utilities are designed to address common programming patterns for improving reliability and performance:

  • The retry function allows for automatically re-attempting a function call a specified number of times, with configurable delays and backoff, to handle transient failures.
  • The Cache class provides a simple in-memory key-value store with a limited size, employing a basic Least Recently Used (LRU)-like eviction strategy to manage its capacity.

As these are in the demo directory, they are suitable for experimentation and may be integrated into the main project or moved to a dedicated utils module in the future, following further review and enhancement.

Examples

Using the retry function

import random
import time
from demo.docs_demo import retry # Assuming appropriate import path

def unreliable_operation():
    """Simulates an operation that might fail randomly."""
    if random.random() < 0.7: # 70% chance of failure
        raise ValueError("Operation failed temporarily!")
    return "Operation successful!"

# Retry the unreliable_operation up to 5 times with a 1-second initial delay, doubling each time.
try:
    result = retry(unreliable_operation, attempts=5, base_delay=1.0, backoff=2.0, exceptions=(ValueError,))
    print(f"Retry succeeded: {result}")
except Exception as e:
    print(f"Retry failed after all attempts: {e}")

# Example of a function that will always succeed on the first try
def always_succeed():
    print("Always successful!")
    return "Instant Success!"

result_success = retry(always_succeed, attempts=3)
print(f"Immediate success: {result_success}")

Using the Cache class

from demo.docs_demo import Cache # Assuming appropriate import path

# Initialize a cache with a max size of 2
my_cache = Cache(max_size=2)

print(f"Cache size: {len(my_cache._store)}") # Current items: 0

my_cache.put("key1", "value1")
my_cache.put("key2", "value2")
print(f"Cache after adding 2 items: {my_cache._store}")
# Expected: {'key1': 'value1', 'key2': 'value2'}
print(f"Order: {my_cache._order}")
# Expected: ['key1', 'key2']

# Accessing an item
print(f"Get key1: {my_cache.get('key1')}")
# Expected: 'value1'

# Adding a new item when cache is full will evict the oldest (key1 in this case)
my_cache.put("key3", "value3")
print(f"Cache after adding key3 (key1 evicted): {my_cache._store}")
# Expected: {'key2': 'value2', 'key3': 'value3'}
print(f"Order: {my_cache._order}")
# Expected: ['key2', 'key3']

# Updating an existing item moves it to the end of the eviction order
my_cache.put("key2", "updated_value2")
print(f"Cache after updating key2: {my_cache._store}")
# Expected: {'key2': 'updated_value2', 'key3': 'value3'}
print(f"Order: {my_cache._order}")
# Expected: ['key3', 'key2'] # key2 moved to end as most recently 'put'

Function and Class Documentation

retry(fn, attempts=3, base_delay=0.5, backoff=2.0, exceptions=(Exception,))

Executes a given function fn, retrying it up to a specified number of attempts if it raises an exception from a defined set.

This function is useful for handling operations that might fail due to transient issues, such as network timeouts, temporary resource unavailability, or database contention. It incorporates an exponential backoff strategy to reduce the load on the failing service during retries.

Parameters

  • fn (callable): The function to be executed and potentially retried. This function should take no arguments. If fn requires arguments, consider wrapping it in a lambda or functools.partial.
  • attempts (int, optional): The maximum number of times to attempt calling fn. Must be a positive integer. Defaults to 3.
  • base_delay (float, optional): The initial delay in seconds before the first retry. Defaults to 0.5.
  • backoff (float, optional): The factor by which the delay increases between successive retries. A value of 2.0 means the delay doubles each time. Defaults to 2.0.
  • exceptions (tuple or type, optional): A single exception type or a tuple of exception types that should trigger a retry. Any other exception type will be re-raised immediately. Defaults to (Exception,), meaning all exceptions will trigger a retry.

Returns

The result of the successful execution of fn.

Side Effects

  • May pause execution using time.sleep() between retry attempts.
  • If fn raises an exception not listed in exceptions, or if all attempts fail, the last encountered exception is re-raised.

Raises

The last exception caught during the retry loop if all attempts are exhausted.

class Cache

A simple, in-memory key-value cache with a fixed maximum size and an LRU-ish eviction policy.

This cache is suitable for storing frequently accessed data to reduce computational load or I/O operations, provided the data can fit within the specified max_size. The eviction policy prioritizes items that have been least recently put into the cache when new items need to be stored and the cache is full.

__init__(self, max_size=128)

Initializes a new Cache instance.

Parameters
  • max_size (int, optional): The maximum number of key-value pairs the cache can hold. Must be a positive integer. Defaults to 128.

get(self, key)

Retrieves the value associated with the given key from the cache.

Parameters
  • key (Hashable): The key of the item to retrieve.
Returns

The value associated with the key if found, otherwise None.

put(self, key, value)

Stores a value associated with a key in the cache.

If the cache is full (len(self._store) >= self.max_size) and the key is not already present, the least recently put item (based on insertion order tracking) will be evicted to make room for the new item. If the key already exists, its value is updated, and its position is moved to the "most recently put" end of the eviction order.

Parameters
  • key (Hashable): The key for the item to store.
  • value (Any): The value to store.
Returns

None.

Side Effects
  • Adds or updates an entry in the cache.
  • May evict an existing entry if the cache is at its max_size and a new key is being added.

Migration or Upgrade Notes

This pull request introduces new files and features in the demo directory. There are no breaking changes or modifications to existing core functionalities, so no specific migration or upgrade steps are required for existing users. These utilities are new additions and can be integrated into existing projects at discretion.


This is an AI-generated documentation draft. Please review, edit, and commit changes as appropriate.

Response generated using gemini-2.5-flash

@dvirdung dvirdung changed the title Demo: aido docs (v1.3.2) Demo: aido docs Jul 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant