Problem/Motivation

UsageProviderFilter::getValueOptions() and UsageModelFilter::getValueOptions() run an uncached SELECT DISTINCT against ai_metering_usage on every request. The in-memory guard (if (isset($this->valueOptions))) does not survive between page loads, so every admin user hitting the log view triggers two redundant queries — including a full table scan on model_id, which has no index.

Steps to reproduce

  1. Enable query logging (Devel or WebProfiler).
  2. Load /admin/reports/ai-metering/log in two separate sessions.
  3. Observe SELECT DISTINCT provider_id FROM {ai_metering_usage} running on every load.

Proposed resolution

Cache the options with a Cache::PERMANENT entry tagged ai_metering:usage, invalidated when a new usage record is written:

use Drupal\Core\Cache\Cache;

public function getValueOptions(): void {
  if (isset($this->valueOptions)) {
    return;
  }
  $cid = 'ai_metering:filter_options:providers';
  if ($cached = \Drupal::cache()->get($cid)) {
    $this->valueOptions = $cached->data;
    return;
  }
  // ... existing SELECT DISTINCT query ...
  \Drupal::cache()->set($cid, $this->valueOptions, Cache::PERMANENT, ['ai_metering:usage']);
}

Inject CacheBackendInterface for testability rather than using the static call.

Remaining tasks

  • Apply the pattern to both UsageProviderFilter and UsageModelFilter
  • Add Cache::invalidateTags(['ai_metering:usage']) in the usage record writer
  • Extend ViewsFilterTest to assert cache hit on second call

UI / API / Data model changes

Internal change only. No visible impact on the filter dropdowns.

AI assistance

Cache strategy and proposed code drafted with AI assistance and reviewed by the module maintainer.

Comments

codeitwisely created an issue. See original summary.

  • codeitwisely committed 7456b4be on 1.0.x
    Issue #3605212: Cache Views filter option queries with ai_metering_usage...
codeitwisely’s picture

Status: Active » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.