objectcache: use INTERIM_KEY_TTL constant in WANObjectCache for readability
[lhc/web/wiklou.git] / includes / libs / objectcache / WANObjectCache.php
index c6aac9a..db27e42 100644 (file)
@@ -19,6 +19,7 @@
  * @ingroup Cache
  */
 
+use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
 use Psr\Log\LoggerAwareInterface;
 use Psr\Log\LoggerInterface;
 use Psr\Log\NullLogger;
@@ -88,6 +89,8 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
        protected $purgeRelayer;
        /** @var LoggerInterface */
        protected $logger;
+       /** @var StatsdDataFactoryInterface */
+       protected $stats;
 
        /** @var int ERR_* constant for the "last error" registry */
        protected $lastRelayError = self::ERR_NONE;
@@ -108,6 +111,9 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
 
        /** Seconds to keep dependency purge keys around */
        const CHECK_KEY_TTL = self::TTL_YEAR;
+       /** Seconds to keep interim value keys for tombstoned keys around */
+       const INTERIM_KEY_TTL = 1;
+
        /** Seconds to keep lock keys around */
        const LOCK_TTL = 10;
        /** Default remaining TTL at which to consider pre-emptive regeneration */
@@ -132,6 +138,11 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
        const TTL_LAGGED = 30;
        /** Idiom for delete() for "no hold-off" */
        const HOLDOFF_NONE = 0;
+       /** Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL" */
+       const STALE_TTL_NONE = 0;
+       /** Idiom for set()/getWithSetCallback() for "no post-expired grace period" */
+       const GRACE_TTL_NONE = 0;
+
        /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
        const MIN_TIMESTAMP_NONE = 0.0;
 
@@ -177,6 +188,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         *   - channels : Map of (action => channel string). Actions include "purge".
         *   - relayers : Map of (action => EventRelayer object). Actions include "purge".
         *   - logger   : LoggerInterface object
+        *   - stats    : LoggerInterface object
         */
        public function __construct( array $params ) {
                $this->cache = $params['cache'];
@@ -187,6 +199,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                        ? $params['relayers']['purge']
                        : new EventRelayerNull( [] );
                $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
+               $this->stats = isset( $params['stats'] ) ? $params['stats'] : new NullStatsdDataFactory();
        }
 
        public function setLogger( LoggerInterface $logger ) {
@@ -199,7 +212,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         * @return WANObjectCache
         */
        public static function newEmpty() {
-               return new self( [
+               return new static( [
                        'cache'   => new EmptyBagOStuff(),
                        'pool'    => 'empty'
                ] );
@@ -239,7 +252,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         * Consider using getWithSetCallback() instead of get() and set() cycles.
         * That method has cache slam avoiding features for hot/expensive keys.
         *
-        * @param string $key Cache key
+        * @param string $key Cache key made from makeKey() or makeGlobalKey()
         * @param mixed &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
         * @param array $checkKeys List of "check" keys
         * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
@@ -260,7 +273,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         *
         * @see WANObjectCache::get()
         *
-        * @param array $keys List of cache keys
+        * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
         * @param array &$curTTLs Map of (key => approximate TTL left) for existing keys [returned]
         * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
         *  keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
@@ -306,7 +319,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                        $wrappedValues += $this->cache->getMulti( $keysGet );
                }
                // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
-               $now = microtime( true );
+               $now = $this->getCurrentTime();
 
                // Collect timestamps from all "check" keys
                $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
@@ -421,28 +434,30 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         *      they certainly should not see ones that ended up getting rolled back.
         *      Default: false
         *   - lockTSE : if excessive replication/snapshot lag is detected, then store the value
-        *      with this TTL and flag it as stale. This is only useful if the reads for
-        *      this key use getWithSetCallback() with "lockTSE" set.
+        *      with this TTL and flag it as stale. This is only useful if the reads for this key
+        *      use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
+        *      then it will still add on to this TTL in the excessive lag scenario.
         *      Default: WANObjectCache::TSE_NONE
         *   - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
         *      methods return such stale values with a $curTTL of 0, and getWithSetCallback()
         *      will call the regeneration callback in such cases, passing in the old value
         *      and its as-of time to the callback. This is useful if adaptiveTTL() is used
         *      on the old value's as-of time when it is verified as still being correct.
-        *      Default: 0.
+        *      Default: WANObjectCache::STALE_TTL_NONE.
         * @note Options added in 1.28: staleTTL
         * @return bool Success
         */
        final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
-               $now = microtime( true );
+               $now = $this->getCurrentTime();
                $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
+               $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : self::STALE_TTL_NONE;
                $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
                $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
-               $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : 0;
 
                // Do not cache potentially uncommitted data as it might get rolled back
                if ( !empty( $opts['pending'] ) ) {
-                       $this->logger->info( "Rejected set() for $key due to pending writes." );
+                       $this->logger->info( 'Rejected set() for {cachekey} due to pending writes.',
+                               [ 'cachekey' => $key ] );
 
                        return true; // no-op the write for being unsafe
                }
@@ -456,16 +471,19 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                                $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
                        // Case B: any long-running transaction; ignore this set()
                        } elseif ( $age > self::MAX_READ_LAG ) {
-                               $this->logger->info( "Rejected set() for $key due to snapshot lag." );
+                               $this->logger->info( 'Rejected set() for {cachekey} due to snapshot lag.',
+                                       [ 'cachekey' => $key ] );
 
                                return true; // no-op the write for being unsafe
                        // Case C: high replication lag; lower TTL instead of ignoring all set()s
                        } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
                                $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
-                               $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
+                               $this->logger->warning( 'Lowered set() TTL for {cachekey} due to replication lag.',
+                                       [ 'cachekey' => $key ] );
                        // Case D: medium length request with medium replication lag; ignore this set()
                        } else {
-                               $this->logger->info( "Rejected set() for $key due to high read lag." );
+                               $this->logger->info( 'Rejected set() for {cachekey} due to high read lag.',
+                                       [ 'cachekey' => $key ] );
 
                                return true; // no-op the write for being unsafe
                        }
@@ -581,7 +599,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                        $time = $purge[self::FLD_TIME];
                } else {
                        // Casting assures identical floats for the next getCheckKeyTime() calls
-                       $now = (string)microtime( true );
+                       $now = (string)$this->getCurrentTime();
                        $this->cache->add( $key,
                                $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
                                self::CHECK_KEY_TTL
@@ -600,20 +618,21 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         * on all keys that should be changed. When get() is called on those
         * keys, the relevant "check" keys must be supplied for this to work.
         *
-        * The "check" key essentially represents a last-modified field.
-        * When touched, the field will be updated on all cache servers.
-        * Keys using it via get(), getMulti(), or getWithSetCallback() will
-        * be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
-        * by those methods to avoid race conditions where dependent keys get updated
-        * with stale values (e.g. from a DB replica DB).
-        *
-        * This is typically useful for keys with hardcoded names or in some cases
-        * dynamically generated names where a low number of combinations exist.
-        * When a few important keys get a large number of hits, a high cache
-        * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
-        * method is less appropriate in such cases since the "time since expiry"
-        * cannot be inferred, causing any get() after the reset to treat the key
-        * as being "hot", resulting in more stale value usage.
+        * The "check" key essentially represents a last-modified time of an entity.
+        * When the key is touched, the timestamp will be updated to the current time.
+        * Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will
+        * be invalidated. This approach is useful if many keys depend on a single entity.
+        *
+        * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
+        * future by get*() methods in order to avoid race conditions where keys are updated
+        * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
+        * key, making it possible to know the timestamp of the last change to the corresponding
+        * entities in most cases. This might use more cache space than resetCheckKey().
+        *
+        * When a few important keys get a large number of hits, a high cache time is usually
+        * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
+        * in such cases since the "time since expiry" cannot be inferred, causing any get()
+        * after the reset to treat the key as being "hot", resulting in more stale value usage.
         *
         * Note that "check" keys won't collide with other regular keys.
         *
@@ -644,12 +663,9 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         *        to, any temporary ejection of that server will cause the value to be
         *        seen as purged as a new server will initialize the "check" key.
         *
-        * The advantage is that this does not place high TTL keys on every cache
-        * server, making it better for code that will cache many different keys
-        * and either does not use lockTSE or uses a low enough TTL anyway.
-        *
-        * This is typically useful for keys with dynamically generated names
-        * where a high number of combinations exist.
+        * The advantage here is that the "check" keys, which have high TTLs, will only
+        * be created when a get*() method actually uses that key. This is better when
+        * a large number of "check" keys are invalided in a short period of time.
         *
         * Note that "check" keys won't collide with other regular keys.
         *
@@ -799,15 +815,23 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         * @see WANObjectCache::get()
         * @see WANObjectCache::set()
         *
-        * @param string $key Cache key
+        * @param string $key Cache key made from makeKey() or makeGlobalKey()
         * @param int $ttl Seconds to live for key updates. Special values are:
-        *   - WANObjectCache::TTL_INDEFINITE: Cache forever
-        *   - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
+        *   - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
+        *   - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
         * @param callable $callback Value generation function
         * @param array $opts Options map:
         *   - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
-        *      touchCheckKey() or resetCheckKey() is called on any of these keys.
+        *      touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
+        *      is useful if thousands or millions of keys depend on the same entity. The entity can
+        *      simply have its "check" key updated whenever the entity is modified.
         *      Default: [].
+        *   - graceTTL: Consider reusing expired values instead of refreshing them if they expired
+        *      less than this many seconds ago. The odds of a refresh becomes more likely over time,
+        *      becoming certain once the grace period is reached. This can reduce traffic spikes
+        *      when millions of keys are compared to the same "check" key and touchCheckKey()
+        *      or resetCheckKey() is called on that "check" key.
+        *      Default: WANObjectCache::GRACE_TTL_NONE.
         *   - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
         *      ago, then try to have a single thread handle cache regeneration at any given time.
         *      Other threads will try to use stale values if possible. If, on miss, the time since
@@ -842,19 +866,26 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         *      This is useful if the source of a key is suspected of having possibly changed
         *      recently, and the caller wants any such changes to be reflected.
         *      Default: WANObjectCache::MIN_TIMESTAMP_NONE.
-        *   - hotTTR: Expected time-till-refresh (TTR) for keys that average ~1 hit/second (1 Hz).
-        *      Keys with a hit rate higher than 1Hz will refresh sooner than this TTR and vise versa.
-        *      Such refreshes won't happen until keys are "ageNew" seconds old. The TTR is useful at
+        *   - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
+        *      second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
+        *      TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
+        *      This uses randomization to avoid triggering cache stampedes. The TTR is useful at
         *      reducing the impact of missed cache purges, since the effect of a heavily referenced
         *      key being stale is worse than that of a rarely referenced key. Unlike simply lowering
-        *      $ttl, seldomly used keys are largely unaffected by this option, which makes it possible
-        *      to have a high hit rate for the "long-tail" of less-used keys.
+        *      $ttl, seldomly used keys are largely unaffected by this option, which makes it
+        *      possible to have a high hit rate for the "long-tail" of less-used keys.
         *      Default: WANObjectCache::HOT_TTR.
         *   - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
         *      than this. It becomes more likely over time, becoming certain once the key is expired.
+        *      This helps avoid cache stampedes that might be triggered due to the key expiring.
         *      Default: WANObjectCache::LOW_TTL.
         *   - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
         *      Default: WANObjectCache::AGE_NEW.
+        *   - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
+        *      miss the callback may get $oldValue/$oldAsOf values for keys that have already been
+        *      expired for this specified time. This is useful if adaptiveTTL() is used on the old
+        *      value's as-of time when it is verified as still being correct.
+        *      Default: WANObjectCache::STALE_TTL_NONE
         * @return mixed Value found or written to the key
         * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
         * @note Callable type hints are not used to avoid class-autoloading
@@ -886,11 +917,14 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                                        use ( $callback, $version ) {
                                                if ( is_array( $oldValue )
                                                        && array_key_exists( self::VFLD_DATA, $oldValue )
+                                                       && array_key_exists( self::VFLD_VERSION, $oldValue )
+                                                       && $oldValue[self::VFLD_VERSION] === $version
                                                ) {
                                                        $oldData = $oldValue[self::VFLD_DATA];
                                                } else {
                                                        // VFLD_DATA is not set if an old, unversioned, key is present
                                                        $oldData = false;
+                                                       $oldAsOf = null;
                                                }
 
                                                return [
@@ -908,7 +942,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                                        // Value existed before with a different version; use variant key.
                                        // Reflect purges to $key by requiring that this key value be newer.
                                        $value = $this->doGetWithSetCallback(
-                                               'cache-variant:' . md5( $key ) . ":$version",
+                                               $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), $version ),
                                                $ttl,
                                                $callback,
                                                // Regenerate value if not newer than $key
@@ -944,6 +978,8 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
        protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
                $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
                $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
+               $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : self::STALE_TTL_NONE;
+               $graceTTL = isset( $opts['graceTTL'] ) ? $opts['graceTTL'] : self::GRACE_TTL_NONE;
                $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
                $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
                $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR;
@@ -951,19 +987,24 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE;
                $versioned = isset( $opts['version'] );
 
+               // Get a collection name to describe this class of key
+               $kClass = $this->determineKeyClass( $key );
+
                // Get the current key value
                $curTTL = null;
                $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
                $value = $cValue; // return value
 
-               $preCallbackTime = microtime( true );
+               $preCallbackTime = $this->getCurrentTime();
                // Determine if a cached value regeneration is needed or desired
                if ( $value !== false
-                       && $curTTL > 0
+                       && $this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
                        && $this->isValid( $value, $versioned, $asOf, $minTime )
                        && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
                        && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $preCallbackTime )
                ) {
+                       $this->stats->increment( "wanobjectcache.$kClass.hit.good" );
+
                        return $value;
                }
 
@@ -971,7 +1012,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                $isTombstone = ( $curTTL !== null && $value === false );
                if ( $isTombstone && $lockTSE <= 0 ) {
                        // Use the INTERIM value for tombstoned keys to reduce regeneration load
-                       $lockTSE = 1;
+                       $lockTSE = self::INTERIM_KEY_TTL;
                }
                // Assume a key is hot if requested soon after invalidation
                $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
@@ -990,6 +1031,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                                // Lock acquired; this thread should update the key
                                $lockAcquired = true;
                        } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
+                               $this->stats->increment( "wanobjectcache.$kClass.hit.stale" );
                                // If it cannot be acquired; then the stale value can be used
                                return $value;
                        } else {
@@ -998,10 +1040,14 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                                // use the INTERIM value from the last thread that regenerated it.
                                $value = $this->getInterimValue( $key, $versioned, $minTime, $asOf );
                                if ( $value !== false ) {
+                                       $this->stats->increment( "wanobjectcache.$kClass.hit.volatile" );
+
                                        return $value;
                                }
                                // Use the busy fallback value if nothing else
                                if ( $busyValue !== null ) {
+                                       $this->stats->increment( "wanobjectcache.$kClass.miss.busy" );
+
                                        return is_callable( $busyValue ) ? $busyValue() : $busyValue;
                                }
                        }
@@ -1025,7 +1071,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                // so use a special INTERIM key to pass the new value around threads.
                if ( ( $isTombstone && $lockTSE > 0 ) && $valueIsCacheable ) {
                        $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
-                       $newAsOf = microtime( true );
+                       $newAsOf = $this->getCurrentTime();
                        $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
                        // Avoid using set() to avoid pointless mcrouter broadcasting
                        $this->setInterimValue( $key, $wrapped, $tempTTL );
@@ -1033,6 +1079,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
 
                if ( $valueIsCacheable ) {
                        $setOpts['lockTSE'] = $lockTSE;
+                       $setOpts['staleTTL'] = $staleTTL;
                        // Use best known "since" timestamp if not provided
                        $setOpts += [ 'since' => $preCallbackTime ];
                        // Update the cache; this will fail if the key is tombstoned
@@ -1044,6 +1091,8 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                        $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, (int)$preCallbackTime - 60 );
                }
 
+               $this->stats->increment( "wanobjectcache.$kClass.miss.compute" );
+
                return $value;
        }
 
@@ -1056,7 +1105,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         */
        protected function getInterimValue( $key, $versioned, $minTime, &$asOf ) {
                $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
-               list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
+               list( $value ) = $this->unwrap( $wrapped, $this->getCurrentTime() );
                if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
                        $asOf = $wrapped[self::FLD_TIME];
 
@@ -1367,21 +1416,23 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
 
        /**
         * @see BagOStuff::makeKey()
-        * @param string $keys,... Key component (starting with a key collection name)
+        * @param string $class Key class
+        * @param string $component [optional] Key component (starting with a key collection name)
         * @return string Colon-delimited list of $keyspace followed by escaped components of $args
         * @since 1.27
         */
-       public function makeKey() {
+       public function makeKey( $class, $component = null ) {
                return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
        }
 
        /**
         * @see BagOStuff::makeGlobalKey()
-        * @param string $keys,... Key component (starting with a key collection name)
+        * @param string $class Key class
+        * @param string $component [optional] Key component (starting with a key collection name)
         * @return string Colon-delimited list of $keyspace followed by escaped components of $args
         * @since 1.27
         */
-       public function makeGlobalKey() {
+       public function makeGlobalKey( $class, $component = null ) {
                return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
        }
 
@@ -1469,6 +1520,46 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         *     $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
         * @endcode
         *
+        * Another use case is when there are no applicable "last modified" fields in the DB,
+        * and there are too many dependencies for explicit purges to be viable, and the rate of
+        * change to relevant content is unstable, and it is highly valued to have the cached value
+        * be as up-to-date as possible.
+        *
+        * Example usage:
+        * @code
+        *     $query = "<some complex query>";
+        *     $idListFromComplexQuery = $cache->getWithSetCallback(
+        *         $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
+        *         GraphQueryClass::STARTING_TTL,
+        *         function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
+        *             $gdb = $this->getReplicaGraphDbConnection();
+        *             // Account for any snapshot/replica DB lag
+        *             $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
+        *
+        *             $newList = iterator_to_array( $gdb->query( $query ) );
+        *             sort( $newList, SORT_NUMERIC ); // normalize
+        *
+        *             $minTTL = GraphQueryClass::MIN_TTL;
+        *             $maxTTL = GraphQueryClass::MAX_TTL;
+        *             if ( $oldValue !== false ) {
+        *                 // Note that $oldAsOf is the last time this callback ran
+        *                 $ttl = ( $newList === $oldValue )
+        *                     // No change: cache for 150% of the age of $oldValue
+        *                     ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
+        *                     // Changed: cache for %50 of the age of $oldValue
+        *                     : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
+        *             }
+        *
+        *             return $newList;
+        *        },
+        *        [
+        *             // Keep stale values around for doing comparisons for TTL calculations.
+        *             // High values improve long-tail keys hit-rates, though might waste space.
+        *             'staleTTL' => GraphQueryClass::GRACE_TTL
+        *        ]
+        *     );
+        * @endcode
+        *
         * @param int|float $mtime UNIX timestamp
         * @param int $maxTTL Maximum TTL (seconds)
         * @param int $minTTL Minimum TTL (seconds); Default: 30
@@ -1485,7 +1576,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                        return $minTTL; // no last-modified time provided
                }
 
-               $age = time() - $mtime;
+               $age = $this->getCurrentTime() - $mtime;
 
                return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
        }
@@ -1512,7 +1603,7 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                if ( $this->purgeRelayer instanceof EventRelayerNull ) {
                        // This handles the mcrouter and the single-DC case
                        $ok = $this->cache->set( $key,
-                               $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
+                               $this->makePurgeValue( $this->getCurrentTime(), self::HOLDOFF_NONE ),
                                $ttl
                        );
                } else {
@@ -1558,23 +1649,56 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                return $ok;
        }
 
+       /**
+        * Check if a key is fresh or in the grace window and thus due for randomized reuse
+        *
+        * If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning
+        * true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds.
+        * This handles widely varying levels of cache access traffic.
+        *
+        * If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.
+        *
+        * @param float $curTTL Approximate TTL left on the key if present
+        * @param int $graceTTL Consider using stale values if $curTTL is greater than this
+        * @return bool
+        */
+       protected function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
+               if ( $curTTL > 0 ) {
+                       return true;
+               } elseif ( $graceTTL <= 0 ) {
+                       return false;
+               }
+
+               $ageStale = abs( $curTTL ); // seconds of staleness
+               $curGTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
+               if ( $curGTTL <= 0 ) {
+                       return false; //  already out of grace period
+               }
+
+               // Chance of using a stale value is the complement of the chance of refreshing it
+               return !$this->worthRefreshExpiring( $curGTTL, $graceTTL );
+       }
+
        /**
         * Check if a key is nearing expiration and thus due for randomized regeneration
         *
-        * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
-        * of returning true increases steadily from 0% to 100% as the $curTTL
-        * moves from $lowTTL to 0 seconds. This handles widely varying
-        * levels of cache access traffic.
+        * This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true
+        * increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds.
+        * This handles widely varying levels of cache access traffic.
+        *
+        * If $curTTL <= 0 (e.g. already expired), then this returns false.
         *
         * @param float $curTTL Approximate TTL left on the key if present
         * @param float $lowTTL Consider a refresh when $curTTL is less than this
         * @return bool
         */
        protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
-               if ( $curTTL >= $lowTTL ) {
+               if ( $lowTTL <= 0 ) {
+                       return false;
+               } elseif ( $curTTL >= $lowTTL ) {
                        return false;
                } elseif ( $curTTL <= 0 ) {
-                       return true;
+                       return false;
                }
 
                $chance = ( 1 - $curTTL / $lowTTL );
@@ -1598,6 +1722,10 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
         * @return bool
         */
        protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
+               if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
+                       return false;
+               }
+
                $age = $now - $asOf;
                $timeOld = $age - $ageNew;
                if ( $timeOld <= 0 ) {
@@ -1709,6 +1837,24 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
                return $res;
        }
 
+       /**
+        * @param string $key String of the format <scope>:<class>[:<class or variable>]...
+        * @return string
+        */
+       protected function determineKeyClass( $key ) {
+               $parts = explode( ':', $key );
+
+               return isset( $parts[1] ) ? $parts[1] : $parts[0]; // sanity
+       }
+
+       /**
+        * @return float UNIX timestamp
+        * @codeCoverageIgnore
+        */
+       protected function getCurrentTime() {
+               return microtime( true );
+       }
+
        /**
         * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
         * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),