Skip to content

Commit 5365902

Browse files
authored
[flutter_svg] Invalidate pending cache entries on clear and evict (#13595)
Rebased on current main (`8041ccab1`), preserving the failed-load fix and its regression test from #13604. This PR adds invalidation of pending loads on `Cache.clear` and `Cache.evict`: an obsolete completion cannot repopulate the cache or remove a replacement request, even when loaders reuse the same Future. Documents pending-load invalidation on both methods. The cache lifecycle tests live in `cache_test.dart`. The shared-Future regression checks that an evicted request does not populate the cache before the replacement's completion callback runs. Preserves synchronous cache hits, coalescing and entry-count LRU. Bumps the package to 2.3.4 with a changelog entry. Related: flutter/flutter#182486 (failed-load cleanup is already on main via #13604). Validation on Windows: `flutter analyze` clean; full `flutter test` suite: 77 passed, 1 existing skip; formatting and `git diff --check` passed. No golden files changed. Overlapping proposals: #13613 also concerns failed pending loads; main already includes #13604. This PR retains that fix and focuses on clear/evict invalidation. #13596 is stacked on this branch and was rebased with it. ## Pre-Review Checklist This draft was prepared with AI assistance and remains pending the contributor's human review and confirmation of the unchecked checklist items.
1 parent 68b3d02 commit 5365902

4 files changed

Lines changed: 148 additions & 30 deletions

File tree

‎third_party/packages/flutter_svg/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 2.3.4
2+
3+
* Prevents pending loads invalidated by clear or evict from repopulating the cache.
4+
15
## 2.3.3
26

37
* Fixes `Cache.putIfAbsent` leaving rejected futures in `_pending` and leaking

‎third_party/packages/flutter_svg/lib/src/cache.dart‎

Lines changed: 43 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
11
import 'package:flutter/foundation.dart';
22
import 'package:vector_graphics_compiler/vector_graphics_compiler.dart';
33

4+
// Eviction can be followed by another request that reuses the same Future.
5+
// Track request identity separately so obsolete callbacks are ignored.
6+
class _PendingLoad {
7+
_PendingLoad(this.future);
8+
9+
final Future<ByteData> future;
10+
}
11+
412
/// The cache for decoded SVGs.
513
class Cache {
6-
final Map<Object, Future<ByteData>> _pending = <Object, Future<ByteData>>{};
14+
final Map<Object, _PendingLoad> _pending = <Object, _PendingLoad>{};
715
final Map<Object, ByteData> _cache = <Object, ByteData>{};
816

917
/// Maximum number of entries to store in the cache.
@@ -35,17 +43,20 @@ class Cache {
3543
}
3644
}
3745

38-
/// Evicts all entries from the cache.
46+
/// Evicts all completed entries and invalidates pending loads.
3947
///
4048
/// This is useful if, for instance, the root asset bundle has been updated
4149
/// and therefore new images must be obtained.
4250
void clear() {
51+
_pending.clear();
4352
_cache.clear();
4453
}
4554

46-
/// Evicts a single entry from the cache, returning true if successful.
55+
/// Evicts a completed entry or invalidates its pending load, returning true if found.
4756
bool evict(Object key) {
48-
return _cache.remove(key) != null;
57+
final hadPending = _pending.remove(key) != null;
58+
final hadCached = _cache.remove(key) != null;
59+
return hadPending || hadCached;
4960
}
5061

5162
/// Evicts a single entry from the cache if the `oldData` and `newData` are
@@ -57,44 +68,47 @@ class Cache {
5768
return evict(key);
5869
}
5970

60-
/// Returns the previously cached [PictureStream] for the given key, if available;
71+
/// Returns the previously cached [ByteData] for the given key, if available;
6172
/// if not, calls the given callback to obtain it first. In either case, the
6273
/// key is moved to the "most recently used" position.
6374
///
6475
/// The arguments must not be null. The `loader` cannot return null.
6576
Future<ByteData> putIfAbsent(Object key, Future<ByteData> Function() loader) {
6677
assert(key != null); // ignore: unnecessary_null_comparison
6778
assert(loader != null); // ignore: unnecessary_null_comparison
68-
Future<ByteData>? pendingResult = _pending[key];
69-
if (pendingResult != null) {
70-
return pendingResult;
79+
80+
final _PendingLoad? pending = _pending[key];
81+
if (pending != null) {
82+
return pending.future;
7183
}
7284

73-
ByteData? result = _cache[key];
74-
if (result != null) {
75-
// Remove the provider from the list so that we can put it back in below
76-
// and thus move it to the end of the list.
77-
_cache.remove(key);
78-
} else {
79-
pendingResult = loader();
80-
_pending[key] = pendingResult;
81-
pendingResult.then(
82-
(ByteData data) {
85+
final ByteData? cached = _cache.remove(key);
86+
if (cached != null) {
87+
_add(key, cached); // Update the LRU order.
88+
return SynchronousFuture<ByteData>(cached);
89+
}
90+
91+
final Future<ByteData> future = loader();
92+
final request = _PendingLoad(future);
93+
_pending[key] = request;
94+
// Observe both outcomes without changing the Future returned to callers.
95+
// An error must not poison subsequent loads or create an unhandled error
96+
// from the otherwise ignored Future returned by then().
97+
future.then<void>(
98+
(ByteData data) {
99+
if (identical(_pending[key], request)) {
83100
_pending.remove(key);
84101
_add(key, data);
85-
result = data; // in case it was a synchronous future.
86-
},
87-
onError: (Object error, StackTrace stackTrace) {
102+
}
103+
},
104+
onError: (Object error, StackTrace stackTrace) {
105+
if (identical(_pending[key], request)) {
88106
_pending.remove(key);
89-
},
90-
);
91-
}
92-
if (result != null) {
93-
_add(key, result!);
94-
return SynchronousFuture<ByteData>(result!);
95-
}
107+
}
108+
},
109+
);
96110
assert(_cache.length <= maximumSize);
97-
return pendingResult!;
111+
return future;
98112
}
99113

100114
void _add(Object key, ByteData result) {

‎third_party/packages/flutter_svg/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: flutter_svg
22
description: An SVG rendering and widget library for Flutter, which allows painting and displaying Scalable Vector Graphics 1.1 files.
33
repository: https://github.com/flutter/packages/tree/main/third_party/packages/flutter_svg
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+flutter_svg%22
5-
version: 2.3.3
5+
version: 2.3.4
66

77
environment:
88
sdk: ^3.11.0

‎third_party/packages/flutter_svg/test/cache_test.dart‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,4 +169,104 @@ void main() {
169169

170170
expect(uncaughtErrors, isEmpty);
171171
});
172+
173+
test('clear prevents pending loads from repopulating stale entries', () async {
174+
final cache = Cache();
175+
final oldLoad = Completer<ByteData>();
176+
final Future<ByteData> oldFuture = cache.putIfAbsent('icon', () => oldLoad.future);
177+
178+
cache.clear();
179+
180+
final replacement = ByteData(3);
181+
expect(
182+
identical(
183+
await cache.putIfAbsent('icon', () => Future<ByteData>.value(replacement)),
184+
replacement,
185+
),
186+
isTrue,
187+
);
188+
189+
oldLoad.complete(ByteData(1));
190+
await oldFuture;
191+
expect(cache.count, 1);
192+
193+
final ByteData cached = await cache.putIfAbsent(
194+
'icon',
195+
() => throw StateError('stale load replaced the cache'),
196+
);
197+
expect(identical(cached, replacement), isTrue);
198+
});
199+
200+
test('evict invalidates in-flight loads as well as completed loads', () async {
201+
final cache = Cache();
202+
final oldLoad = Completer<ByteData>();
203+
final Future<ByteData> oldFuture = cache.putIfAbsent('icon', () => oldLoad.future);
204+
205+
expect(cache.evict('icon'), isTrue);
206+
expect(cache.evict('icon'), isFalse);
207+
oldLoad.complete(ByteData(1));
208+
await oldFuture;
209+
expect(cache.count, 0);
210+
211+
final fresh = ByteData(2);
212+
await cache.putIfAbsent('icon', () => Future<ByteData>.value(fresh));
213+
expect(cache.count, 1);
214+
expect(cache.evict('icon'), isTrue);
215+
expect(cache.count, 0);
216+
});
217+
218+
test('an evicted request cannot cache a Future reused by a later request', () async {
219+
final cache = Cache();
220+
final shared = Completer<ByteData>();
221+
final Future<ByteData> first = cache.putIfAbsent('icon', () => shared.future);
222+
expect(cache.evict('icon'), isTrue);
223+
224+
final Future<int> countBetweenCallbacks = shared.future.then((_) => cache.count);
225+
final Future<ByteData> second = cache.putIfAbsent('icon', () => shared.future);
226+
227+
final data = ByteData(1);
228+
shared.complete(data);
229+
expect(await first, same(data));
230+
expect(await countBetweenCallbacks, 0);
231+
expect(await second, same(data));
232+
expect(cache.count, 1);
233+
});
234+
235+
test('an invalidated failure leaves the replacement pending load intact', () async {
236+
final cache = Cache();
237+
final obsolete = Completer<ByteData>();
238+
final current = Completer<ByteData>();
239+
final Future<ByteData> oldFuture = cache.putIfAbsent('icon', () => obsolete.future);
240+
final Future<void> expectedFailure = expectLater(oldFuture, throwsStateError);
241+
cache.evict('icon');
242+
final Future<ByteData> currentFuture = cache.putIfAbsent('icon', () => current.future);
243+
244+
obsolete.completeError(StateError('obsolete request failed'));
245+
await expectedFailure;
246+
expect(
247+
identical(currentFuture, cache.putIfAbsent('icon', () => throw StateError('duplicate'))),
248+
isTrue,
249+
);
250+
251+
final fresh = ByteData(2);
252+
current.complete(fresh);
253+
await currentFuture;
254+
expect(await cache.putIfAbsent('icon', () => throw StateError('missing cache')), same(fresh));
255+
});
256+
257+
test('disabling and restoring cache invalidates requests from before disabling', () async {
258+
final cache = Cache();
259+
final obsolete = Completer<ByteData>();
260+
final Future<ByteData> oldFuture = cache.putIfAbsent('icon', () => obsolete.future);
261+
cache.maximumSize = 0;
262+
cache.maximumSize = 100;
263+
264+
obsolete.complete(ByteData(1));
265+
await oldFuture;
266+
expect(cache.count, 0);
267+
268+
final fresh = ByteData(2);
269+
expect(await cache.putIfAbsent('icon', () => SynchronousFuture<ByteData>(fresh)), same(fresh));
270+
expect(cache.count, 1);
271+
});
172272
}

0 commit comments

Comments
 (0)