1 package org.apache.lucene.util;
3 * Copyright 2009 The Apache Software Foundation
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
26 import org.apache.lucene.index.IndexReader;
27 import org.apache.lucene.search.FieldCache;
28 import org.apache.lucene.search.FieldCache.CacheEntry;
31 * Provides methods for sanity checking that entries in the FieldCache
32 * are not wasteful or inconsistent.
35 * Lucene 2.9 Introduced numerous enhancements into how the FieldCache
36 * is used by the low levels of Lucene searching (for Sorting and
37 * ValueSourceQueries) to improve both the speed for Sorting, as well
38 * as reopening of IndexReaders. But these changes have shifted the
39 * usage of FieldCache from "top level" IndexReaders (frequently a
40 * MultiReader or DirectoryReader) down to the leaf level SegmentReaders.
41 * As a result, existing applications that directly access the FieldCache
42 * may find RAM usage increase significantly when upgrading to 2.9 or
43 * Later. This class provides an API for these applications (or their
44 * Unit tests) to check at run time if the FieldCache contains "insane"
45 * usages of the FieldCache.
47 * @lucene.experimental
49 * @see FieldCacheSanityChecker.Insanity
50 * @see FieldCacheSanityChecker.InsanityType
52 public final class FieldCacheSanityChecker {
54 private RamUsageEstimator ramCalc = null;
55 public FieldCacheSanityChecker() {
59 * If set, will be used to estimate size for all CacheEntry objects
62 public void setRamUsageEstimator(RamUsageEstimator r) {
68 * Quick and dirty convenience method
71 public static Insanity[] checkSanity(FieldCache cache) {
72 return checkSanity(cache.getCacheEntries());
76 * Quick and dirty convenience method that instantiates an instance with
77 * "good defaults" and uses it to test the CacheEntrys
80 public static Insanity[] checkSanity(CacheEntry... cacheEntries) {
81 FieldCacheSanityChecker sanityChecker = new FieldCacheSanityChecker();
82 // doesn't check for interned
83 sanityChecker.setRamUsageEstimator(new RamUsageEstimator(false));
84 return sanityChecker.check(cacheEntries);
89 * Tests a CacheEntry[] for indication of "insane" cache usage.
91 * <B>NOTE:</b>FieldCache CreationPlaceholder objects are ignored.
92 * (:TODO: is this a bad idea? are we masking a real problem?)
95 public Insanity[] check(CacheEntry... cacheEntries) {
96 if (null == cacheEntries || 0 == cacheEntries.length)
97 return new Insanity[0];
99 if (null != ramCalc) {
100 for (int i = 0; i < cacheEntries.length; i++) {
101 cacheEntries[i].estimateSize(ramCalc);
105 // the indirect mapping lets MapOfSet dedup identical valIds for us
107 // maps the (valId) identityhashCode of cache values to
108 // sets of CacheEntry instances
109 final MapOfSets<Integer, CacheEntry> valIdToItems = new MapOfSets<Integer, CacheEntry>(new HashMap<Integer, Set<CacheEntry>>(17));
110 // maps ReaderField keys to Sets of ValueIds
111 final MapOfSets<ReaderField, Integer> readerFieldToValIds = new MapOfSets<ReaderField, Integer>(new HashMap<ReaderField, Set<Integer>>(17));
114 // any keys that we know result in more then one valId
115 final Set<ReaderField> valMismatchKeys = new HashSet<ReaderField>();
117 // iterate over all the cacheEntries to get the mappings we'll need
118 for (int i = 0; i < cacheEntries.length; i++) {
119 final CacheEntry item = cacheEntries[i];
120 final Object val = item.getValue();
122 if (val instanceof FieldCache.CreationPlaceholder)
125 final ReaderField rf = new ReaderField(item.getReaderKey(),
126 item.getFieldName());
128 final Integer valId = Integer.valueOf(System.identityHashCode(val));
130 // indirect mapping, so the MapOfSet will dedup identical valIds for us
131 valIdToItems.put(valId, item);
132 if (1 < readerFieldToValIds.put(rf, valId)) {
133 valMismatchKeys.add(rf);
137 final List<Insanity> insanity = new ArrayList<Insanity>(valMismatchKeys.size() * 3);
139 insanity.addAll(checkValueMismatch(valIdToItems,
142 insanity.addAll(checkSubreaders(valIdToItems,
143 readerFieldToValIds));
145 return insanity.toArray(new Insanity[insanity.size()]);
149 * Internal helper method used by check that iterates over
150 * valMismatchKeys and generates a Collection of Insanity
151 * instances accordingly. The MapOfSets are used to populate
152 * the Insanity objects.
153 * @see InsanityType#VALUEMISMATCH
155 private Collection<Insanity> checkValueMismatch(MapOfSets<Integer, CacheEntry> valIdToItems,
156 MapOfSets<ReaderField, Integer> readerFieldToValIds,
157 Set<ReaderField> valMismatchKeys) {
159 final List<Insanity> insanity = new ArrayList<Insanity>(valMismatchKeys.size() * 3);
161 if (! valMismatchKeys.isEmpty() ) {
162 // we have multiple values for some ReaderFields
164 final Map<ReaderField, Set<Integer>> rfMap = readerFieldToValIds.getMap();
165 final Map<Integer, Set<CacheEntry>> valMap = valIdToItems.getMap();
166 for (final ReaderField rf : valMismatchKeys) {
167 final List<CacheEntry> badEntries = new ArrayList<CacheEntry>(valMismatchKeys.size() * 2);
168 for(final Integer value: rfMap.get(rf)) {
169 for (final CacheEntry cacheEntry : valMap.get(value)) {
170 badEntries.add(cacheEntry);
174 CacheEntry[] badness = new CacheEntry[badEntries.size()];
175 badness = badEntries.toArray(badness);
177 insanity.add(new Insanity(InsanityType.VALUEMISMATCH,
178 "Multiple distinct value objects for " +
179 rf.toString(), badness));
186 * Internal helper method used by check that iterates over
187 * the keys of readerFieldToValIds and generates a Collection
188 * of Insanity instances whenever two (or more) ReaderField instances are
189 * found that have an ancestry relationships.
191 * @see InsanityType#SUBREADER
193 private Collection<Insanity> checkSubreaders( MapOfSets<Integer, CacheEntry> valIdToItems,
194 MapOfSets<ReaderField, Integer> readerFieldToValIds) {
196 final List<Insanity> insanity = new ArrayList<Insanity>(23);
198 Map<ReaderField, Set<ReaderField>> badChildren = new HashMap<ReaderField, Set<ReaderField>>(17);
199 MapOfSets<ReaderField, ReaderField> badKids = new MapOfSets<ReaderField, ReaderField>(badChildren); // wrapper
201 Map<Integer, Set<CacheEntry>> viToItemSets = valIdToItems.getMap();
202 Map<ReaderField, Set<Integer>> rfToValIdSets = readerFieldToValIds.getMap();
204 Set<ReaderField> seen = new HashSet<ReaderField>(17);
206 Set<ReaderField> readerFields = rfToValIdSets.keySet();
207 for (final ReaderField rf : readerFields) {
209 if (seen.contains(rf)) continue;
211 List<Object> kids = getAllDecendentReaderKeys(rf.readerKey);
212 for (Object kidKey : kids) {
213 ReaderField kid = new ReaderField(kidKey, rf.fieldName);
215 if (badChildren.containsKey(kid)) {
216 // we've already process this kid as RF and found other problems
217 // track those problems as our own
218 badKids.put(rf, kid);
219 badKids.putAll(rf, badChildren.get(kid));
220 badChildren.remove(kid);
222 } else if (rfToValIdSets.containsKey(kid)) {
223 // we have cache entries for the kid
224 badKids.put(rf, kid);
231 // every mapping in badKids represents an Insanity
232 for (final ReaderField parent : badChildren.keySet()) {
233 Set<ReaderField> kids = badChildren.get(parent);
235 List<CacheEntry> badEntries = new ArrayList<CacheEntry>(kids.size() * 2);
237 // put parent entr(ies) in first
239 for (final Integer value : rfToValIdSets.get(parent)) {
240 badEntries.addAll(viToItemSets.get(value));
244 // now the entries for the descendants
245 for (final ReaderField kid : kids) {
246 for (final Integer value : rfToValIdSets.get(kid)) {
247 badEntries.addAll(viToItemSets.get(value));
251 CacheEntry[] badness = new CacheEntry[badEntries.size()];
252 badness = badEntries.toArray(badness);
254 insanity.add(new Insanity(InsanityType.SUBREADER,
255 "Found caches for decendents of " +
265 * Checks if the seed is an IndexReader, and if so will walk
266 * the hierarchy of subReaders building up a list of the objects
267 * returned by obj.getFieldCacheKey()
269 private List<Object> getAllDecendentReaderKeys(Object seed) {
270 List<Object> all = new ArrayList<Object>(17); // will grow as we iter
272 for (int i = 0; i < all.size(); i++) {
273 Object obj = all.get(i);
274 if (obj instanceof IndexReader) {
275 IndexReader[] subs = ((IndexReader)obj).getSequentialSubReaders();
276 for (int j = 0; (null != subs) && (j < subs.length); j++) {
277 all.add(subs[j].getCoreCacheKey());
282 // need to skip the first, because it was the seed
283 return all.subList(1, all.size());
287 * Simple pair object for using "readerKey + fieldName" a Map key
289 private final static class ReaderField {
290 public final Object readerKey;
291 public final String fieldName;
292 public ReaderField(Object readerKey, String fieldName) {
293 this.readerKey = readerKey;
294 this.fieldName = fieldName;
297 public int hashCode() {
298 return System.identityHashCode(readerKey) * fieldName.hashCode();
301 public boolean equals(Object that) {
302 if (! (that instanceof ReaderField)) return false;
304 ReaderField other = (ReaderField) that;
305 return (this.readerKey == other.readerKey &&
306 this.fieldName.equals(other.fieldName));
309 public String toString() {
310 return readerKey.toString() + "+" + fieldName;
315 * Simple container for a collection of related CacheEntry objects that
316 * in conjunction with each other represent some "insane" usage of the
319 public final static class Insanity {
320 private final InsanityType type;
321 private final String msg;
322 private final CacheEntry[] entries;
323 public Insanity(InsanityType type, String msg, CacheEntry... entries) {
325 throw new IllegalArgumentException
326 ("Insanity requires non-null InsanityType");
328 if (null == entries || 0 == entries.length) {
329 throw new IllegalArgumentException
330 ("Insanity requires non-null/non-empty CacheEntry[]");
334 this.entries = entries;
338 * Type of insane behavior this object represents
340 public InsanityType getType() { return type; }
342 * Description of hte insane behavior
344 public String getMsg() { return msg; }
346 * CacheEntry objects which suggest a problem
348 public CacheEntry[] getCacheEntries() { return entries; }
350 * Multi-Line representation of this Insanity object, starting with
351 * the Type and Msg, followed by each CacheEntry.toString() on it's
352 * own line prefaced by a tab character
355 public String toString() {
356 StringBuilder buf = new StringBuilder();
357 buf.append(getType()).append(": ");
360 if (null != m) buf.append(m);
364 CacheEntry[] ce = getCacheEntries();
365 for (int i = 0; i < ce.length; i++) {
366 buf.append('\t').append(ce[i].toString()).append('\n');
369 return buf.toString();
374 * An Enumeration of the different types of "insane" behavior that
375 * may be detected in a FieldCache.
377 * @see InsanityType#SUBREADER
378 * @see InsanityType#VALUEMISMATCH
379 * @see InsanityType#EXPECTED
381 public final static class InsanityType {
382 private final String label;
383 private InsanityType(final String label) {
387 public String toString() { return label; }
390 * Indicates an overlap in cache usage on a given field
391 * in sub/super readers.
393 public final static InsanityType SUBREADER
394 = new InsanityType("SUBREADER");
398 * Indicates entries have the same reader+fieldname but
399 * different cached values. This can happen if different datatypes,
400 * or parsers are used -- and while it's not necessarily a bug
401 * it's typically an indication of a possible problem.
404 * <bPNOTE:</b> Only the reader, fieldname, and cached value are actually
405 * tested -- if two cache entries have different parsers or datatypes but
406 * the cached values are the same Object (== not just equal()) this method
407 * does not consider that a red flag. This allows for subtle variations
408 * in the way a Parser is specified (null vs DEFAULT_LONG_PARSER, etc...)
411 public final static InsanityType VALUEMISMATCH
412 = new InsanityType("VALUEMISMATCH");
415 * Indicates an expected bit of "insanity". This may be useful for
416 * clients that wish to preserve/log information about insane usage
417 * but indicate that it was expected.
419 public final static InsanityType EXPECTED
420 = new InsanityType("EXPECTED");