본문으로 건너뛰기
cccskills
무료GitHub에 공개

equatable-linkedhashmap-lru-reorder

Fix LRU-bounded Flutter/bloc state classes that silently lose insertion-order updates. Use when: (1) a state class uses `Equatable` with a `LinkedHashMap<K, V>` field to preserve insertion order (LRU, MRU, recent-items caches), (2) `Cubit.emit` appears to drop emissions when an existing key is re-inserted or moved to most-recent, (3) LRU eviction evicts the "wrong" entry after a refresh, (4) a test that reports the same key twice and then overflows the cap sees the refreshed entry evicted instead of the oldest. Root cause: Equatable's default map comparison is structural (unordered), so reordering without changing keys/values produces an "equal" state that `Cubit.emit` suppresses.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md7.9 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Equatable + LinkedHashMap LRU reorder suppression

Problem

A Flutter bloc/cubit state class uses an insertion-ordered LinkedHashMap<K, V> to implement LRU semantics (touch-on-access, evict oldest past a cap). The field is included in props for value equality. When an existing key is re-inserted to move it to most-recent, Cubit.emit drops the new state as equal to the previous one, leaving LRU order stale. On the next insert past the cap, the "touched" entry is evicted instead of the truly oldest one.

This is silent: no errors, no logs. Tests that only check the final status of each key pass. The bug surfaces only when a test specifically asserts that a refreshed key survives a later cap-overflow eviction.

Context / Trigger Conditions

  • State class extends Equatable with a LinkedHashMap<K, V> field
  • LRU behavior implemented via remove(key) + insert to move-to-most-recent
  • props includes the map directly: List<Object?> get props => [_map, ...]
  • Symptoms:
    • blocTest(..., expect: () => hasLength(N)) reports fewer emissions than expected
    • LRU eviction test like "refresh key A, then overflow — expect B evicted" fails with A evicted instead
    • Consumers using BlocListener or context.select don't react to touch-only updates

Solution

Add the keys list to props alongside the map so insertion-order changes produce a distinct state:

@override
List<Object?> get props {
  // Both entries are required.
  //
  // Equatable's default map comparison is structural (unordered), so
  // `_statuses` alone catches value changes but NOT pure LRU reorders
  // where the key/value set is unchanged.
  // `_statuses.keys.toList()` catches those insertion-order changes.
  // Removing either would silently suppress a whole class of state
  // updates — do not "simplify" this.
  return [_statuses, _statuses.keys.toList(), maxEntries];
}

Keep the map in props as well — it catches value-only changes (same key, different value, no reorder). The keys list catches order-only changes. Together they cover both dimensions. Removing either re-opens the bug.

Additional hardening (recommended)

While you're here, also:

  1. Defensive-copy in the constructor if it accepts an externally-built LinkedHashMap. A caller can otherwise retain a reference and mutate the "immutable" state:

    VideoPlaybackStatusState({
      this.maxEntries = _defaultMaxEntries,
      LinkedHashMap<K, V>? statuses,
    }) : _statuses = statuses == null
              ? LinkedHashMap<K, V>()
              : LinkedHashMap<K, V>.from(statuses);
    
  2. Short-circuit redundant writes in the cubit to avoid allocating a new map on every no-op report (e.g. errorBuilder fires every frame during a retry):

    void report(K key, V value) {
      if (state.valueFor(key) == value) return;
      emit(state.withValue(key, value));
    }
    

Verification

Write an explicit props-inequality test that pins the invariant directly, rather than relying on higher-level LRU tests to transitively catch it:

test('states with same entries but different LRU order are not equal', () {
  final a = MyState()
      .withStatus(idA, Status.foo)
      .withStatus(idB, Status.bar);
  final b = MyState()
      .withStatus(idB, Status.bar)
      .withStatus(idA, Status.foo);

  expect(a, isNot(equals(b)));
});

Mutation test: temporarily revert to props: [_map, maxEntries] (no keys list) and run the test. It MUST fail. Restore and confirm pass. This proves the assertion is load-bearing and guards the invariant.

Example

Full state class shape (Dart):

import 'dart:collection';
import 'package:equatable/equatable.dart';

class VideoPlaybackStatusState extends Equatable {
  VideoPlaybackStatusState({
    this.maxEntries = _defaultMaxEntries,
    LinkedHashMap<String, PlaybackStatus>? statuses,
  }) : _statuses = statuses == null
            ? LinkedHashMap<String, PlaybackStatus>()
            : LinkedHashMap<String, PlaybackStatus>.from(statuses);

  static const int _defaultMaxEntries = 100;
  final int maxEntries;
  final LinkedHashMap<String, PlaybackStatus> _statuses;

  PlaybackStatus statusFor(String id) =>
      _statuses[id] ?? PlaybackStatus.ready;

  VideoPlaybackStatusState withStatus(String id, PlaybackStatus status) {
    final next = LinkedHashMap<String, PlaybackStatus>.from(_statuses)
      ..remove(id)
      ..[id] = status;
    while (next.length > maxEntries) {
      next.remove(next.keys.first);
    }
    return VideoPlaybackStatusState(maxEntries: maxEntries, statuses: next);
  }

  @override
  List<Object?> get props => [_statuses, _statuses.keys.toList(), maxEntries];
  //                         ^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^
  //                         catches      catches reorders
  //                         value changes (LRU touches)
}

The LRU test that catches the bug:

test('reporting same id twice moves it to most-recent', () {
  final cubit = VideoPlaybackStatusCubit(maxEntries: 2);
  cubit.report(id1, PlaybackStatus.forbidden);
  cubit.report(id2, PlaybackStatus.ageRestricted);
  cubit.report(id1, PlaybackStatus.forbidden); // refresh id1
  cubit.report(id3, PlaybackStatus.notFound);  // overflow

  // Without the fix: id1 is evicted (wrong — it was just touched)
  // With the fix: id2 is evicted (correct — it's the oldest)
  expect(cubit.state.statusFor(id2), PlaybackStatus.ready);
  expect(cubit.state.statusFor(id1), PlaybackStatus.forbidden);
});

Notes

  • Flutter lint interaction: Using an explicit LinkedHashMap<K, V>() literal trips prefer_collection_literals (the lint wants {}). But {} types as Map<K, V>, not LinkedHashMap, which loses the compile-time guarantee that insertion order is preserved across refactors. Keep the explicit type and suppress the lint locally (// ignore: prefer_collection_literals) if the constructor path triggers it.
  • Applies to any ordered collection in Equatable: Queue, SplayTreeMap, or any structure where order is semantic. Anywhere Equatable compares the structure contents unordered but your code depends on order, you need a secondary props entry that captures the order.
  • Not specific to bloc: the same bug appears with Riverpod's state notifier == checks and any equality-based diffing. Same fix applies.
  • TDD discipline: this bug was only caught because a test specifically asserted "refreshed key survives overflow." A test suite that only checks "status X maps to key Y" after individual writes would pass with the bug intact. When writing tests for ordered-collection state, always include at least one test that exercises the ordering itself (not just membership).

References

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y". Use when: (1) ExternalSecret shows OutOfSync in ArgoCD but won't sync, (2) ArgoCD application status shows "namespace X is not permitted in project 'infrastructure'", (3) ExternalSecret targets a namespace managed by a different ArgoCD project, (4) Using apps-of-apps pattern with separate infrastructure and application projects.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2662026년 10월 19일 업데이트

Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language. After selection, generates AI image prompts and visual briefs section-by-section. Use when the user shares content and needs visual direction, image sourcing, or creative direction for any material.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2662026년 10월 19일 업데이트

Fix "Null check operator used on a null value" errors when an object is set to null during an async await. Use when: (1) Object reference is nullified while awaiting, (2) Code accesses object with ! after await returns, (3) Cancel/dispose operations run concurrently with async operations on same object. Solution: capture local reference before await.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2662026년 10월 19일 업데이트

Add custom metadata headers (x-amz-meta-*) to AWS v4 signed requests for GCS S3-compatible API. Use when: (1) Adding custom metadata to GCS uploads via S3 API, (2) Getting signature mismatch errors after adding new headers, (3) x-amz-meta-* headers being ignored or causing 403 errors. Custom headers MUST be included in canonical headers and signed headers list.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2662026년 10월 19일 업데이트

Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings. Use when: (1) Password authentication fails with correct password, (2) Secret created with `<<< "value"` syntax, (3) Error like "password authentication failed" or "invalid token" despite correct value. Bash here-strings (`<<<`) add a trailing newline that corrupts secrets.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2662026년 10월 19일 업데이트

Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp). Use when: (1) Media moderation, transcoding, or analysis silently skips files from Blossom or content-addressed storage servers, (2) URL extraction from Nostr event tags (imeta, r tags) drops URLs without recognized extensions, (3) CDN fallback URLs append .mp4 but the actual server uses extensionless content-addressed paths like /{sha256}. Common in Nostr video events (kind 34236) where different clients use different URL formats.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2662026년 10월 19일 업데이트

divinevideo의 스킬 모두 보기

이 스킬의 문제 신고