# Project Structure: LLM Accounting

This document provides a detailed overview of the `llm-accounting` project's structure, outlining the purpose of each directory and key files. The aim is to facilitate quick orientation for new contributors and LLM agents, enabling efficient understanding and navigation of the codebase.

## 1. Project Overview

`llm-accounting` is a system designed to track and manage LLM (Large Language Model) usage, including token consumption, costs, and rate limits. It provides a flexible backend system (supporting SQLite and PostgreSQL), a command-line interface (CLI) for interaction, and a robust testing suite.

## 2. Top-Level Files and Directories

Here's a breakdown of the main files and directories at the project root:

-   `.flake8`: Configuration file for `flake8`, a Python code linter, ensuring code quality and style consistency.
-   `.gitignore`: Specifies intentionally untracked files to be ignored by Git.
-   `build.bat`: A Windows batch script, likely used for building or setting up the project.
-   `example.py`: An example script demonstrating how to use the `llm-accounting` library.
-   `LICENSE`: Contains the licensing information for the project.
-   `MANIFEST.in`: Specifies non-Python files to be included in the Python distribution package.
-   `pyproject.toml`: Modern Python project configuration file, used by build systems like Poetry or Hatch.
-   `pytest.ini`: Configuration file for `pytest`, the testing framework, defining test discovery and behavior.
-   `README.md`: The main project README, providing a high-level overview, installation instructions, and basic usage.
-   `release_orchestrator.py`: Script likely responsible for automating release processes, such as version bumping and package publishing.
-   `requirements.txt`: Lists the project's Python dependencies.
-   `setup.py`: Traditional Python setup script for packaging and distribution (often used in conjunction with `pyproject.toml`).
-   `tox.ini`: Configuration file for `tox`, a tool for automating testing and package building in multiple Python environments.
-   `version_manager.py`: Script to manage and update the project's version number.
-   `alembic/`: Contains the Alembic environment and migration scripts for database schema management.
-   `data/`: Directory intended for storing application data, such as SQLite databases or configuration files.
-   `docs/`: Contains project documentation, including this `STRUCTURE.md` file.
-   `htmlcov/`: Directory for HTML coverage reports generated by `pytest-cov`.
-   `logs/`: Directory for storing application logs.
-   `src/`: Contains the main source code of the `llm-accounting` library.
-   `tests/`: Contains all unit and integration tests for the project.

## 3. `src/` Directory

The `src/` directory holds the core logic of the `llm-accounting` library.

### `src/llm_accounting/`

This is the main package for the LLM accounting system.

-   `__init__.py`: Initializes the `llm_accounting` package, making its contents importable.
    -   **`LLMAccounting` class**:
        -   **Purpose**: The main entry point for interacting with the LLM accounting system. It orchestrates operations across different backends and services.
        -   **Dependencies**: Internally uses a backend (e.g., SQLite, PostgreSQL) and the `QuotaService`.
        -   **Key Methods**:
            -   `__init__(...)`: Initializes the LLM Accounting instance, setting up the backend and services.
            -   `__enter__(self)` / `__exit__(...)`: Context manager methods for resource management (e.g., database connection).
            -   `track_usage(...)`: Records LLM usage for a specific model, application, and user.
            -   `get_period_stats(self, start: datetime, end: datetime)`: Retrieves usage statistics for a given time period.
            -   `get_model_stats(self, start: datetime, end: datetime)`: Retrieves usage statistics per model.
            -   `get_model_rankings(...)`: Provides rankings of models based on usage.
            -   `purge(self)`: Cleans up old usage data based on retention policies.
            -   `tail(self, n: int = 10)`: Retrieves the last `n` usage entries.
            -   `check_quota(...)`: Checks if a specific usage would exceed defined quotas/limits.
            -   `set_usage_limit(...)`: Sets a new usage limit.
            -   `get_usage_limits(...)`: Retrieves currently active usage limits.
            -   `delete_usage_limit(self, limit_id: int)`: Deletes a specific usage limit.
            -   `get_db_path(self)`: Returns the path to the database file if applicable (e.g., for SQLite).
-   `audit_log.py`: Manages the auditing of LLM usage, recording events and interactions.
    -   **`AuditLogger` class**:
        -   **Purpose**: Provides an interface for logging various LLM-related events and interactions to the chosen backend.
        -   **Dependencies**: Depends on a `BaseBackend` instance for actual data persistence.
        -   **Key Methods**:
            -   `__init__(self, backend: BaseBackend)`: Initializes the logger with a backend.
            -   `log_event(self, app_name: str, user_name: str, model: str, log_type: str, ...)`: Logs a generic event.
            -   `log_prompt(self, app_name: str, user_name: str, model: str, prompt_text: str, ...)`: Logs an LLM prompt.
            -   `log_response(self, app_name: str, user_name: str, model: str, response_text: str, ...)`: Logs an LLM response.
            -   `get_entries(...)`: Retrieves audit log entries from the backend.

#### `src/llm_accounting/backends/`

This sub-package defines the various database backends supported by the system.

-   `__init__.py`: Initializes the `backends` package.
-   `base.py`: Defines the abstract base classes and interfaces for all backend implementations, ensuring a consistent API.
    -   **`AuditLogEntry` class**: Data class representing an entry in the audit log.
    -   **`UsageEntry` class**: Data class representing a single LLM usage record.
    -   **`UsageStats` class**: Data class representing aggregated usage statistics.
    -   **`BaseBackend` abstract class**:
        -   **Purpose**: Provides a common interface that all concrete backend implementations must adhere to. This ensures interchangeability of backends.
        -   **Key Methods (Abstract)**:
            -   `initialize()`: Sets up the backend (e.g., creates tables, establishes connections).
            -   `insert_usage(entry: UsageEntry)`: Inserts a new usage entry.
            -   `get_period_stats(...)`: Retrieves aggregated usage statistics for a period.
            -   `get_model_stats(...)`: Retrieves usage statistics per model.
            -   `get_model_rankings(...)`: Provides rankings of models based on usage.
            -   `purge()`: Cleans up old data.
            -   `tail(n: int)`: Retrieves the latest usage entries.
            -   `close()`: Closes the backend connection.
            -   `execute_query(query: str)`: Executes a raw query (for advanced use/debugging).
            -   `get_usage_limits(...)`: Retrieves defined usage limits.
            -   `get_accounting_entries_for_quota(...)`: Fetches entries relevant for quota checks.
            -   `insert_usage_limit(...)`: Inserts a new usage limit.
            -   `delete_usage_limit(limit_id: int)`: Deletes a usage limit.
            -   `_ensure_connected()`: Ensures the backend has an active connection.
            -   `initialize_audit_log_schema()`: Initializes the schema for audit logging.
            -   `log_audit_event(entry: AuditLogEntry)`: Logs an audit event.
            -   `get_audit_log_entries(...)`: Retrieves audit log entries.
-   `mock_backend.py`: A mock implementation of the backend, useful for testing and development without a real database.
    -   **`MockBackend` class**:
        -   **Purpose**: Provides an in-memory, non-persistent implementation of `BaseBackend` for testing, development, and scenarios where a real database is not required. It simulates database operations without actual storage.
        -   **Dependencies**: Inherits from `BaseBackend`.
        -   **Key Methods**: Implements all abstract methods from `BaseBackend`, such as `initialize()`, `insert_usage()`, `get_period_stats()`, `purge()`, `tail()`, `close()`, `execute_query()`, `insert_usage_limit()`, `delete_usage_limit()`, `get_usage_limits()`, `get_accounting_entries_for_quota()`, `get_usage_costs()`. These methods operate on in-memory data structures.
-   `postgresql.py`: Implements the PostgreSQL backend, handling database interactions for PostgreSQL using SQLAlchemy ORM models.
    -   **`PostgreSQLBackend` class**:
        -   **Purpose**: Provides a concrete implementation of `BaseBackend` for PostgreSQL databases. It manages connections, schema creation, and all data operations for PostgreSQL.
        -   **Dependencies**: Inherits from `BaseBackend`. Relies on `psycopg2` (or similar PostgreSQL driver) for database connectivity.
        -   **Key Methods**: Implements all abstract methods from `BaseBackend`. `initialize()` now uses SQLAlchemy's `create_engine` and `Base.metadata.create_all` for schema setup, and `close()` disposes the engine. Data operations leverage SQLAlchemy connections and ORM models.
-   `sqlite_queries.py`: Contains SQL query definitions specific to the SQLite backend.
    -   **Purpose**: Provides a centralized location for SQL query strings and functions to generate them, used by the `SQLiteBackend`. This separation improves maintainability and readability.
    -   **Key Functions**:
        -   `insert_usage_query(...)`: Generates the SQL for inserting usage data.
        -   `get_period_stats_query(...)`: Generates the SQL for retrieving period statistics.
        -   `get_model_stats_query(...)`: Generates the SQL for retrieving model statistics.
        -   `get_model_rankings_query(...)`: Generates the SQL for retrieving model rankings.
        -   `tail_query(...)`: Generates the SQL for retrieving the latest usage entries.
-   `sqlite_utils.py`: Utility functions for the SQLite backend. **Note: Database schema initialization is now handled by SQLAlchemy's `Base.metadata.create_all` during backend initialization, and migrations are managed by Alembic.**
    -   **Purpose**: Provides helper functions for SQLite database operations, such as schema initialization and path validation.
    -   **Key Functions**:
        -   `validate_db_filename(filename: str)`: Validates if a given filename is suitable for a SQLite database.
-   `sqlite.py`: Implements the SQLite backend, handling database interactions for SQLite using SQLAlchemy ORM models.
    -   **`SQLiteBackend` class**:
        -   **Purpose**: Provides a concrete implementation of `BaseBackend` for SQLite databases. It manages connections, schema creation, and all data operations for SQLite.
        -   **Dependencies**: Inherits from `BaseBackend`. Relies on Python's built-in `sqlite3` module.
        -   **Key Methods**: Implements all abstract methods from `BaseBackend`. `initialize()` now uses SQLAlchemy's `create_engine` and `Base.metadata.create_all` for schema setup, and `close()` manages the SQLAlchemy connection. Data operations leverage SQLAlchemy connections and ORM models.
-   `csv_backend.py`: Implements the CSV backend, storing accounting data in CSV files.
    -   **`CSVBackend` class**: Provides a concrete implementation of `BaseBackend` using CSV files for data storage. Manages CSV file creation, reading, and writing for accounting entries, usage limits, and audit logs.

##### `src/llm_accounting/backends/mock_backend_parts/`

Components specific to the mock backend.

-   `connection_manager.py`: Manages mock database connections.
    -   **`MockConnectionManager` class**:
        -   **Purpose**: Handles the simulated connection lifecycle for the `MockBackend`.
        -   **Key Methods**:
            -   `_ensure_connected()`: Simulates ensuring a connection is active.
            -   `initialize()`: Simulates initialization of the connection.
            -   `close()`: Simulates closing the connection.
-   `limit_manager.py`: Handles mock limit enforcement.
    -   **`MockLimitManager` class**:
        -   **Purpose**: Manages the simulated enforcement and retrieval of usage limits for the `MockBackend`.
        -   **Key Methods**:
            -   `insert_usage_limit(...)`: Simulates inserting a usage limit.
            -   `delete_usage_limit(...)`: Simulates deleting a usage limit.
            -   `get_usage_limits(...)`: Simulates retrieving usage limits.
            -   `get_accounting_entries_for_quota(...)`: Simulates fetching entries for quota checks.
-   `query_executor.py`: Executes mock queries.
    -   **`MockQueryExecutor` class**:
        -   **Purpose**: Simulates the execution of raw queries against the `MockBackend`'s in-memory data.
        -   **Key Methods**:
            -   `execute_query(query: str)`: Processes a given query string and returns a simulated result.
-   `stats_manager.py`: Manages mock usage statistics.
    -   **`MockStatsManager` class**:
        -   **Purpose**: Handles the simulated retrieval of usage statistics for the `MockBackend`.
        -   **Key Methods**:
            -   `get_period_stats(...)`: Simulates retrieving aggregated usage statistics for a period.
            -   `get_model_stats(...)`: Simulates retrieving usage statistics per model.
            -   `get_model_rankings(...)`: Simulates providing rankings of models based on usage.
            -   `get_usage_costs(...)`: Simulates retrieving usage costs.
-   `usage_manager.py`: Manages mock usage data.
    -   **`MockUsageManager` class**:
        -   **Purpose**: Handles the simulated insertion, purging, and retrieval of raw usage data for the `MockBackend`.
        -   **Key Methods**:
            -   `insert_usage(...)`: Simulates inserting a new usage entry.
            -   `purge()`: Simulates purging old usage data.
            -   `tail(n: int)`: Simulates retrieving the latest usage entries.

##### `src/llm_accounting/backends/postgresql_backend_parts/`

Components specific to the PostgreSQL backend.

-   `connection_manager.py`: Manages PostgreSQL database connections.
    -   **`ConnectionManager` class**:
        -   **Purpose**: Handles the connection lifecycle for the `PostgreSQLBackend`, including establishing, closing, and ensuring active connections.
        -   **Key Methods**:
            -   `initialize()`: Establishes the initial database connection.
            -   `close()`: Closes the database connection.
            -   `ensure_connected()`: Ensures that a database connection is active, re-establishing if necessary.
-   `data_deleter.py`: Handles deletion of data in PostgreSQL.
    -   **`DataDeleter` class**:
        -   **Purpose**: Manages the deletion of usage data and limits within the PostgreSQL backend.
        -   **Key Methods**:
            -   `delete_usage_limit(limit_id: int)`: Deletes a specific usage limit by its ID.
            -   `purge()`: Deletes old usage data based on defined retention policies.
-   `data_inserter.py`: Handles insertion of data into PostgreSQL.
    -   **`DataInserter` class**:
        -   **Purpose**: Manages the insertion of usage data, usage limits, and audit log entries into the PostgreSQL database.
        -   **Key Methods**:
            -   `insert_usage(entry: UsageEntry)`: Inserts a new LLM usage record.
            -   `insert_usage_limit(limit: UsageLimit)`: Inserts a new usage limit.
            -   `insert_audit_log_event(entry: AuditLogEntry)`: Inserts a new audit log event.
-   `limit_manager.py`: Manages limit enforcement for PostgreSQL.
    -   **`LimitManager` class**:
        -   **Purpose**: Handles the management and retrieval of usage limits specific to the PostgreSQL backend. It interacts with `DataInserter` to persist limits.
        -   **Dependencies**: Depends on `DataInserter` for inserting limits.
        -   **Key Methods**:
            -   `get_usage_limits(...)`: Retrieves defined usage limits from the database.
            -   `insert_usage_limit(...)`: Inserts a new usage limit into the database.
            -   `set_usage_limit(...)`: Sets or updates a usage limit for a user/project.
            -   `get_usage_limit(...)`: Retrieves a specific usage limit for a user/project.
-   `query_executor.py`: Executes queries against PostgreSQL.
    -   **`QueryExecutor` class**:
        -   **Purpose**: Provides methods for executing various queries against the PostgreSQL database, including retrieving statistics, tailing entries, and executing raw SQL.
        -   **Key Methods**:
            -   `get_period_stats(...)`: Retrieves aggregated usage statistics for a period.
            -   `get_model_stats(...)`: Retrieves usage statistics per model.
            -   `get_model_rankings(...)`: Provides rankings of models based on usage.
            -   `tail(n: int)`: Retrieves the latest usage entries.
            -   `get_usage_limits(...)`: Retrieves defined usage limits.
            -   `get_accounting_entries_for_quota(...)`: Fetches entries relevant for quota checks.
            -   `execute_query(query: str)`: Executes a raw SQL query.
            -   `get_usage_costs(...)`: Retrieves usage costs for a user.
            -   `set_usage_limit(...)`: Sets a usage limit.
            -   `get_usage_limit(...)`: Retrieves a specific usage limit.
            -   `get_audit_log_entries(...)`: Retrieves audit log entries.
-   `query_reader.py`: Reads data from PostgreSQL.
    -   **`QueryReader` class**:
        -   **Purpose**: Focuses on reading and retrieving various types of data from the PostgreSQL database, such as usage statistics, model rankings, and raw usage entries.
        -   **Key Methods**:
            -   `get_period_stats(...)`: Retrieves aggregated usage statistics for a period.
            -   `get_model_stats(...)`: Retrieves usage statistics per model.
            -   `get_model_rankings(...)`: Provides rankings of models based on usage.
            -   `tail(n: int)`: Retrieves the latest usage entries.
            -   `execute_query(query: str)`: Executes a raw SQL query.
            -   `get_usage_costs(...)`: Retrieves usage costs for a user.
-   `quota_reader.py`: Reads quota-related data from PostgreSQL.
    -   **`QuotaReader` class**:
        -   **Purpose**: Specializes in retrieving data necessary for quota and limit checks from the PostgreSQL database.
        -   **Key Methods**:
            -   `get_accounting_entries_for_quota(...)`: Fetches specific accounting entries required to evaluate current usage against defined quotas.
-   `schema_manager.py`: Manages the database schema for PostgreSQL. **Note: Direct DDL operations (table creation, migrations) are now handled by Alembic and SQLAlchemy's `Base.metadata.create_all` during backend initialization.** This module now primarily serves as a placeholder for potential future schema validation or inspection utilities.
    -   **`SchemaManager` class**:
        -   **Purpose**: Responsible for managing the database schema for the PostgreSQL backend, including creating tables and ensuring the schema is up-to-date.
        -   **Key Methods**: (No direct DDL methods. Class kept for potential future schema-related utilities.)

#### `src/llm_accounting/cli/`

This sub-package contains the command-line interface (CLI) implementation.

-   `main.py`: The entry point for the CLI application.
    -   **Purpose**: Defines the main function that sets up the argument parser and dispatches commands to the appropriate handlers.
    -   **Key Functions**:
        -   `main()`: The primary function executed when the `llm-accounting` CLI is invoked. It parses command-line arguments and calls the relevant command function.
-   `parsers.py`: Defines argument parsers for CLI commands.
    -   **Purpose**: Contains functions responsible for setting up and configuring argument parsers for various CLI commands using `argparse`.
    -   **Key Functions**:
        -   `add_stats_parser(subparsers)`: Adds argument parser for the `stats` command.
        -   `add_purge_parser(subparsers)`: Adds argument parser for the `purge` command.
        -   `add_tail_parser(subparsers)`: Adds argument parser for the `tail` command.
        -   `add_select_parser(subparsers)`: Adds argument parser for the `select` command.
        -   `add_track_parser(subparsers)`: Adds argument parser for the `track` command.
        -   `add_limits_parser(subparsers)`: Adds argument parser for the `limits` command.
-   `utils.py`: Utility functions used by the CLI.
    -   **Purpose**: Provides common utility functions for the CLI, such as formatting output and a decorator for handling the `LLMAccounting` instance.
    -   **Key Functions**:
        -   `format_float(value: float)`: Formats a float value for display.
        -   `format_time(value: float)`: Formats a time value for display.
        -   `format_tokens(value: int)`: Formats a token count for display.
        -   `get_accounting()`: Retrieves an instance of `LLMAccounting`.
        -   `with_accounting(f)`: A decorator that injects an `LLMAccounting` instance into CLI command functions.

##### `src/llm_accounting/cli/commands/`

Individual CLI commands.

-   `limits.py`: CLI command for managing and viewing usage limits.
    -   **Purpose**: Implements the CLI subcommands for setting, listing, and deleting usage limits.
    -   **Key Functions**:
        -   `set_limit(args: argparse.Namespace, accounting: LLMAccounting)`: Sets a new usage limit.
        -   `list_limits(args: argparse.Namespace, accounting: LLMAccounting)`: Lists all active usage limits.
        -   `delete_limit(args: argparse.Namespace, accounting: LLMAccounting)`: Deletes a specific usage limit.
-   `purge.py`: CLI command for purging old usage data.
    -   **Purpose**: Implements the CLI command for purging historical LLM usage data from the backend.
    -   **Key Functions**:
        -   `run_purge(args, accounting: LLMAccounting)`: Executes the purge operation, typically removing data older than a specified retention period.
-   `select.py`: CLI command for querying and selecting usage data.
    -   **Purpose**: Implements the CLI command for querying and retrieving LLM usage data based on various criteria.
    -   **Key Functions**:
        -   `run_select(args, accounting: LLMAccounting)`: Executes a data selection query and displays the results.
-   `stats.py`: CLI command for displaying usage statistics.
    -   **Purpose**: Implements the CLI command for retrieving and displaying aggregated LLM usage statistics.
    -   **Key Functions**:
        -   `run_stats(args, accounting: LLMAccounting)`: Executes the statistics retrieval and formats the output for display.
-   `tail.py`: CLI command for tailing (monitoring) real-time usage.
    -   **Purpose**: Implements the CLI command for continuously monitoring and displaying new LLM usage entries as they occur.
    -   **Key Functions**:
        -   `run_tail(args, accounting: LLMAccounting)`: Starts a real-time feed of new usage entries.
-   `track.py`: CLI command for tracking LLM usage.
    -   **Purpose**: Implements the CLI command for manually tracking LLM usage, allowing users to record usage events directly.
    -   **Key Functions**:
        -   `run_track(args, accounting: LLMAccounting)`: Records a new LLM usage entry based on provided command-line arguments.

#### `src/llm_accounting/models/`

Defines data models used throughout the application.

-   `__init__.py`: Initializes the `models` package.
-   `base.py`: Base models or common model utilities.
-   `accounting.py`: Defines the SQLAlchemy ORM model for `AccountingEntry`, representing individual LLM usage records.
-   `audit.py`: Defines the SQLAlchemy ORM model for `AuditLogEntryModel`, representing detailed audit log entries.
-   `limits.py`: Data models for defining and managing usage limits.
    -   **Purpose**: Defines the data structures (Enums and classes) used to represent and manage usage limits within the system.
    -   **Key Enums**:
        -   `LimitScope(Enum)`: Defines the scope of a limit (e.g., GLOBAL, USER, PROJECT, MODEL).
        -   `LimitType(Enum)`: Defines the type of limit (e.g., COST, TOKEN_COUNT, REQUEST_COUNT).
        -   `TimeInterval(Enum)`: Defines the time interval for recurring limits (e.g., DAILY, MONTHLY, ANNUALLY).
    -   **Key Classes**:
        -   `UsageLimitDTO`: A Data Transfer Object (DTO) for usage limit data, used for transferring limit information between layers.
        -   `UsageLimit(Base)`: The SQLAlchemy model for persisting usage limits in the database.
            -   **Key Methods**:
                -   `time_delta()`: Calculates the `timedelta` object corresponding to the `TimeInterval`.

#### `src/llm_accounting/services/`

Contains business logic and services.

-   `quota_service.py`: Provides services related to quota management and enforcement.
    -   **`QuotaService` class**:
        -   **Purpose**: Encapsulates the business logic for checking and enforcing LLM usage quotas and limits across different scopes (global, user, project, model, caller).
        -   **Dependencies**: Depends on a `BaseBackend` instance to retrieve accounting entries and limit definitions.
        -   **Key Methods**:
            -   `__init__(self, backend: BaseBackend)`: Initializes the service with a backend.
            -   `check_quota(...)`: The main method to evaluate if a new usage would exceed any applicable limits.
            -   `_check_global_limits(...)`: Internal method to check global limits.
            -   `_check_model_limits(...)`: Internal method to check model-specific limits.
            -   `_check_project_limits(...)`: Internal method to check project-specific limits.
            -   `_check_user_limits(...)`: Internal method to check user-specific limits.
            -   `_check_caller_limits(...)`: Internal method to check caller-specific limits.
            -   `_check_user_caller_limits(...)`: Internal method to check combined user-caller limits.
            -   `_evaluate_limits(...)`: Generic internal method to evaluate a set of limits against current usage.
            -   `_get_period_start(...)`: Helper to calculate the start time of a given time interval.

## 4. `tests/` Directory

This directory contains all tests for the `llm-accounting` project, organized to mirror the `src/` directory structure.

-   `__init__.py`: Initializes the `tests` package.
-   `conftest.py`: Contains fixtures and hooks for `pytest` that are shared across multiple test files.
-   `test_audit_log.py`: Tests for the `audit_log` module.
-   `test_migrations.py`: Tests for the Alembic database migration system.

### `tests/accounting/`

Tests related to the core accounting logic.

-   `test_global_limits.py`: Tests for global usage limits.
-   `test_model_limits.py`: Tests for limits specific to LLM models.
-   `test_multiple_limit_types.py`: Tests scenarios involving multiple types of limits.
-   `test_user_caller_limits.py`: Tests for limits based on user or caller identity.

### `tests/api_compatibility/`

Tests to ensure API compatibility.

-   `test_audit_logger_api.py`: Tests the API of the audit logger.
-   `test_cli_api.py`: Tests the public API of the CLI.
-   `test_llm_accounting_api.py`: Tests the main `llm-accounting` library API.

### `tests/backends/`

Tests for the various backend implementations.

-   `mock_backends.py`: Tests specific to the mock backend.
-   `test_base.py`: Tests for the base backend interfaces.
-   `test_postgresql.py`: Tests for the PostgreSQL backend.
-   `test_sqlite.py`: Tests for the SQLite backend.
-   `test_csv_backend.py`: Contains unit tests for the `CSVBackend`.
-   `test_usage_models.py`: Tests for usage-related data models.

#### `tests/backends/postgresql_backend_tests/`

Detailed tests for the PostgreSQL backend.

-   `__init__.py`: Initializes the package.
-   `base_test_postgresql.py`: Base test classes for PostgreSQL tests.
-   `test_postgresql_audit_log.py`: Tests audit logging in PostgreSQL.
-   `test_postgresql_init_and_connection.py`: Tests initialization and connection to PostgreSQL.
-   `test_postgresql_query_delegation.py`: Tests query delegation in PostgreSQL.
-   `test_postgresql_query_execution.py`: Tests query execution in PostgreSQL.
-   `test_postgresql_quota_accounting.py`: Tests quota accounting in PostgreSQL.
-   `test_postgresql_usage_insertion.py`: Tests usage data insertion in PostgreSQL.
-   `test_postgresql_usage_limits.py`: Tests usage limits enforcement in PostgreSQL.

#### `tests/backends/sqlite_backend_tests/`

Detailed tests for the SQLite backend.

-   `conftest.py`: Fixtures specific to SQLite backend tests.
-   `test_sqlite_audit_log.py`: Tests audit logging in SQLite.
-   `test_sqlite_init_and_usage.py`: Tests initialization and basic usage of SQLite backend.
-   `test_sqlite_stats_and_purge.py`: Tests statistics and purging functionality in SQLite.
-   `test_sqlite_usage_limits.py`: Tests usage limits enforcement in SQLite.

### `tests/cli/`

Tests for the command-line interface.

-   `test_cli_limits_project.py`: Tests the `limits` CLI command.
-   `test_cli_purge.py`: Tests the `purge` CLI command.
-   `test_cli_stats.py`: Tests the `stats` CLI command.
-   `test_cli_tail.py`: Tests the `tail` CLI command.
-   `test_cli_track.py`: Tests the `track` CLI command.
-   `test_cli_version.py`: Tests the CLI version command.
-   `test_select_project.py`: Tests the `select` CLI command.

#### `tests/cli/test_select/`

Tests for the `select` CLI command's specific functionalities.

-   `__init__.py`: Initializes the package.
-   `conftest.py`: Fixtures specific to `select` command tests.

##### `tests/cli/test_select/select/`

Further granular tests for the `select` command.

-   `__init__.py`: Initializes the package.
-   `conftest.py`: Fixtures specific to these granular `select` tests.
-   `test_aggregation.py`: Tests aggregation queries with `select`.
-   `test_basic_query.py`: Tests basic `select` queries.
-   `test_no_results.py`: Tests `select` command behavior when no results are found.
-   `test_non_select_query.py`: Tests `select` command behavior with non-select queries (should fail or be handled).
-   `test_output_formatting.py`: Tests the formatting of `select` command output.
-   `test_syntax_error.py`: Tests `select` command error handling for syntax errors.

### `tests/core/`

Tests for core accounting functionalities.

-   `__init__.py`: Initializes the package.
-   `test_accounting_purge.py`: Tests the core purge logic.
-   `test_accounting_stats.py`: Tests the core statistics generation logic.
-   `test_accounting_tracking.py`: Tests the core usage tracking logic.
-   `test_accounting_validation.py`: Tests validation rules for accounting data.
-   `test_project_quota_service.py`: Tests the project-level quota service.
-   `test_quota_service.py`: Tests the general quota service.

## 5. `docs/` Directory

This directory is dedicated to project documentation.

-   `STRUCTURE.md`: This file, detailing the project's directory and file structure.

## 6. `data/` Directory

This directory is intended for storing application data. In a typical setup, this might include:

-   SQLite database files (e.g., `llm_accounting.db`).
-   Configuration files that are not part of the source code.

## 7. `logs/` Directory

This directory is used for storing application logs generated during runtime. These logs are crucial for debugging, monitoring, and understanding the application's behavior.
