You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@phoenix.apache.org by ortutay <gi...@git.apache.org> on 2018/04/17 21:53:15 UTC

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

GitHub user ortutay opened a pull request:

    https://github.com/apache/phoenix/pull/298

    PHOENIX-4666 Persistent subquery cache for hash joins

    

You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/ortutay/phoenix PHOENIX-4666-subquery-cache

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/phoenix/pull/298.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #298
    
----
commit 77460c37697b2a112cf6ed345356a16da08dd51c
Author: Marcell Ortutay <mo...@...>
Date:   2018-03-29T19:59:03Z

    PHOENIX-4666 Persistent subquery cache for hash joins

commit d1fc310e3d0df772c0aeb1673d2b64d01f495d27
Author: Marcell Ortutay <mo...@...>
Date:   2018-04-17T20:51:00Z

    PHOENIX-4666 Add tests for TenantCacheTest

----


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    One last git ammend to clean up whitespace. The backport patch has cleaned up whitespace as well.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784854
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/iterate/TableResultIterator.java ---
    @@ -194,13 +194,10 @@ public Tuple next() throws SQLException {
                                 if (retry <= 0) {
                                     throw e1;
                                 }
    +                            Long cacheId = ((HashJoinCacheNotFoundException) e1).getCacheId();
                                 retry--;
                                 try {
    -                                Long cacheId = ((HashJoinCacheNotFoundException) e1).getCacheId();
    -
    -                                ServerCache cache = caches == null ? null :
    --- End diff --
    
    reverted, I think this was accidentally changed during git rebase.


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by twdsilva <gi...@git.apache.org>.
Github user twdsilva commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    LGTM can you click submit patch so we can get a test run?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r188777276
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +153,164 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        return CacheBuilder.newBuilder()
    +            .expireAfterAccess(ttl, TimeUnit.MILLISECONDS)
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry maybeGet(ImmutableBytesPtr cacheId) {
    +        maybePromote(cacheId);
    +        CacheEntry entry = getServerCaches().getIfPresent(cacheId);
    +        return entry;
    +    }
    +
    +    private void maybePromote(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry == null) {
    +            return;
    +        }
    +        getServerCaches().put(cacheId, entry);
    +    }
    +    
    +    private void maybeDemote(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getServerCaches().getIfPresent(cacheId);
    +        if (entry == null) {
    +            return;
    +        }
    +        entry.decrementLiveQueryCount();
    +        if (!entry.isLive()) {
    +            getServerCaches().invalidate(cacheId);
    +        }
    +    }
    +    
    +    public void debugPrintCaches() {
    +		System.out.println("Live cache:" + getServerCaches());
    +		for (ImmutableBytesPtr key : getServerCaches().asMap().keySet()) {
    +			System.out.println("- " + Hex.encodeHexString(key.get()) +
    +					" -> " + getServerCaches().getIfPresent(key).size +
    +					" lq:" + getServerCaches().getIfPresent(key).liveQueriesCount +
    +					" " + Hex.encodeHexString(getServerCaches().getIfPresent(key).cachePtr.get()));
    +		}
    +		System.out.println("Persistent cache:" + getPersistentServerCaches());
    +		for (ImmutableBytesPtr key : getPersistentServerCaches().asMap().keySet()) {
    +			System.out.println("- " + Hex.encodeHexString(key.get()) +
    +					" -> " + getPersistentServerCaches().getIfPresent(key).size +
    +					" " + Hex.encodeHexString(getPersistentServerCaches().getIfPresent(key).cachePtr.get()));
    +		}
    +	}
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = maybeGet(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
         
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public boolean checkServerCache(ImmutableBytesPtr cacheId, boolean shouldIncrementLiveQueryCount) {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        CacheEntry entry = maybeGet(cacheId);
    +        if (entry != null && shouldIncrementLiveQueryCount) {
    +        	entry.incrementLiveQueryCount();
    +        }
    +		return entry != null;
    +    }
    +    
    +    @Override
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
    +        getServerCaches().cleanUp();
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        int size = cachePtr.getLength() + txState.length;
    +        if (size > available) {
    +            evictInactiveEntries(Math.max(size - available + EVICTION_MARGIN_BYTES, EVICTION_MARGIN_BYTES));
    +        }
    +        MemoryChunk chunk = this.getMemoryManager().allocate(size);
             boolean success = false;
             try {
    -            Closeable element = cacheFactory.newCache(cachePtr, txState, chunk, useProtoForIndexMaintainer, clientVersion);
    -            getServerCaches().put(cacheId, element);
    +            CacheEntry entry;
    +            synchronized(this) {
    +                entry = maybeGet(cacheId);
    +                if (entry == null) {
    +                    entry = new CacheEntry(
    +                            cacheId, cachePtr, cacheFactory, txState, chunk,
    +                            usePersistentCache, useProtoForIndexMaintainer,
    +                            clientVersion);
    +                    getServerCaches().put(cacheId, entry);
    +                    available = this.getMemoryManager().getAvailableMemory();
    +                    if (usePersistentCache) {
    +                        getPersistentServerCaches().put(cacheId, entry);
    +                    }
    +                }
    +                entry.incrementLiveQueryCount();
    +            }
                 success = true;
    -            return element;
    +            return entry;
             } finally {
                 if (!success) {
                     Closeables.closeAllQuietly(Collections.singletonList(chunk));
                 }
    -        }           
    +        }
         }
    -    
    +
         @Override
    -    public void removeServerCache(ImmutableBytesPtr cacheId) {
    -        getServerCaches().invalidate(cacheId);
    +    synchronized public void removeServerCache(ImmutableBytesPtr cacheId) {
    --- End diff --
    
    Yea good point, removed `maybeDemote`


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784880
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/memory/GlobalMemoryManager.java ---
    @@ -17,6 +17,8 @@
      */
     package org.apache.phoenix.memory;
     
    +import java.util.Arrays;
    --- End diff --
    
    done


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by JamesRTaylor <gi...@git.apache.org>.
Github user JamesRTaylor commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r195421295
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/iterate/BaseResultIterators.java ---
    @@ -1305,14 +1305,25 @@ public ScanWrapper(Scan scan) {
                                 Scan oldScan = scanPair.getFirst();
                                 byte[] startKey = oldScan.getAttribute(SCAN_ACTUAL_START_ROW);
                                 if(e2 instanceof HashJoinCacheNotFoundException){
    +                                System.out.println("Handling HashJoinCacheNotFoundException");
    --- End diff --
    
    Minor nit: change to log message or remove System.out.println calls


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    @JamesRTaylor @maryannxue is this OK to merge in? I believe all review comments have been addressed, and we've been using this at 23andMe already on custom branch


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784379
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        int size = cachePtr.getLength() + txState.length;
    +        if (size > available) {
    +            evictInactiveEntries(Math.max(size - available + EVICTION_MARGIN_BYTES, EVICTION_MARGIN_BYTES));
    --- End diff --
    
    Good point, in fact the check is right above :). Removed the redundant `max`


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183133702
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/compile/QueryCompiler.java ---
    @@ -383,7 +384,7 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo
                             new PTable[]{lhsTable}, new int[]{fieldPosition}, postJoinFilterExpression, QueryUtil.getOffsetLimit(limit, offset));
                     Pair<Expression, Expression> keyRangeExpressions = new Pair<Expression, Expression>(null, null);
                     getKeyExpressionCombinations(keyRangeExpressions, context, joinTable.getStatement(), rhsTableRef, type, joinExpressions, hashExpressions);
    -                return HashJoinPlan.create(joinTable.getStatement(), rhsPlan, joinInfo, new HashSubPlan[]{new HashSubPlan(0, lhsPlan, hashExpressions, false, keyRangeExpressions.getFirst(), keyRangeExpressions.getSecond())});
    +                return HashJoinPlan.create(joinTable.getStatement(), rhsPlan, joinInfo, new HashSubPlan[]{new HashSubPlan(0, lhsPlan, hashExpressions, false, false, keyRangeExpressions.getFirst(), keyRangeExpressions.getSecond())});
    --- End diff --
    
    This is also hash-join but with left table as build side. I think we should be able to use persistent cache as well. And could you also add another test to cover this point?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183127442
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/ServerCacheClient.java ---
    @@ -216,22 +234,146 @@ public void close() throws SQLException {
                     }
                 }
             }
    -        
    +    }
    +    
    +    public ServerCache checkServerCache(final byte[] cacheId, ScanRanges keyRanges, final TableRef cacheUsingTableRef,
    --- End diff --
    
    I am thinking here, can we do this differently?
    Instead of making RPC calls of "checkServerCache" for the first and every subsequent queries, we do NOT make any calls, neither "check" or "add" when the persistent-cache hint is available and catches the {{PersistentCacheNotFoundException}} on the first attempt (or later attempts if somehow the cache has been evicted) and then try adding the cache all over again. I think it will be more efficient in general.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211400310
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    --- End diff --
    
    nit: formatting


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211399293
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    --- End diff --
    
    Also, how about filtering out `CacheEntry` which are `!isAlive()`?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r188461941
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/ServerCacheClient.java ---
    @@ -216,22 +234,146 @@ public void close() throws SQLException {
                     }
                 }
             }
    -        
    +    }
    +    
    +    public ServerCache checkServerCache(final byte[] cacheId, ScanRanges keyRanges, final TableRef cacheUsingTableRef,
    --- End diff --
    
    Yea makes sense. For this, I'm thinking of modifying the retry logic in BaseResultIterators to disable persistent caching on retries. I'm thinking I can add a get/set'er pair to the "context" that can be used for this


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by dbwong <gi...@git.apache.org>.
Github user dbwong commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211430186
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java ---
    @@ -241,8 +251,35 @@ public TaskExecutionMetricsHolder getTaskExecutionMetric() {
             if (statement.getInnerSelectStatement() != null && postFilter != null) {
                 iterator = new FilterResultIterator(iterator, postFilter);
             }
    -        
    -        return iterator;
    +
    +        if (hasSubPlansWithPersistentCache) {
    +            return peekForPersistentCache(iterator, scanGrouper, scan);
    +        } else {
    +            return iterator;
    +        }
    +    }
    +
    +    private ResultIterator peekForPersistentCache(ResultIterator iterator, ParallelScanGrouper scanGrouper, Scan scan) throws SQLException {
    --- End diff --
    
    Is there a test for this retry logic with the setDisablePersistenCache that I'm missing?  I don't see error path testing.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211992579
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    --- End diff --
    
    > since the two maps have a pointer to the same memory chunk.
    
    Ah, that's the rub. I assumed that when the persistentCaches was used, there would increased memory consumption over when they were not used. If memory use is constant (or at least, negligible), then I agree with you.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211402317
  
    --- Diff: phoenix-core/src/it/java/org/apache/phoenix/end2end/join/HashJoinPersistentCacheIT.java ---
    @@ -0,0 +1,137 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + * http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.phoenix.end2end.join;
    +
    +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
    +import static org.junit.Assert.assertEquals;
    +
    +import java.sql.Connection;
    +import java.sql.DriverManager;
    +import java.sql.ResultSet;
    +import java.util.Properties;
    +
    +import org.apache.phoenix.end2end.join.HashJoinCacheIT.InvalidateHashCache;
    +import org.apache.phoenix.util.PropertiesUtil;
    +import org.apache.phoenix.util.SchemaUtil;
    +import org.apache.phoenix.util.TestUtil;
    +import org.junit.Test;
    +
    +public class HashJoinPersistentCacheIT extends BaseJoinIT {
    +
    +    @Override
    +    protected String getTableName(Connection conn, String virtualName) throws Exception {
    +        String realName = super.getTableName(conn, virtualName);
    +        TestUtil.addCoprocessor(conn, SchemaUtil.normalizeFullTableName(realName), InvalidateHashCache.class);
    +        return realName;
    +    }
    +                
    +    @Test
    +    public void testPersistentCache() throws Exception {
    --- End diff --
    
    This is a very nice test!


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211401519
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/join/HashCacheFactory.java ---
    @@ -25,18 +25,22 @@
     import java.io.IOException;
     import java.sql.SQLException;
     import java.util.ArrayList;
    +import java.util.Arrays;
     import java.util.Collections;
     import java.util.HashMap;
     import java.util.LinkedList;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import net.jcip.annotations.Immutable;
     
    +import org.apache.commons.codec.binary.Hex;
    --- End diff --
    
    Remove


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by dbwong <gi...@git.apache.org>.
Github user dbwong commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211432802
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java ---
    @@ -494,19 +540,37 @@ public ServerCache execute(HashJoinPlan parent) throws SQLException {
                 if (hashExpressions != null) {
                     ResultIterator iterator = plan.iterator();
                     try {
    -                    cache =
    -                            parent.hashClient.addHashCache(ranges, iterator,
    -                                plan.getEstimatedSize(), hashExpressions, singleValueOnly,
    +                    final byte[] cacheId;
    +                    String queryString = plan.getStatement().toString().replaceAll("\\$[0-9]+", "\\$");
    +                    if (usePersistentCache) {
    +                        cacheId = Arrays.copyOfRange(digest.digest(queryString.getBytes()), 0, 8);
    +                        boolean disablePersistentCache = parent.delegate.getContext().getDisablePersistentCache(Bytes.toLong(cacheId));
    +                        if (!disablePersistentCache) {
    +                            try {
    +                                cache = parent.hashClient.createServerCache(cacheId, parent.delegate);
    +                            } catch (IOException e) {
    +                                throw new RuntimeException(e);
    +                            }
    +                        }
    +                    } else {
    +                        cacheId = Bytes.toBytes(RANDOM.nextLong());
    +                    }
    +                    System.out.println("Using cache ID " + Hex.encodeHexString(cacheId) + " for " + queryString);
    +                    if (cache == null) {
    --- End diff --
    
    If disablePersistentCache == true this addHashCace is still using the cacheId from the query string as opposed to a randomID.  Is this intended?  Will this affect the future interactions with that cache?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211783478
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    --- End diff --
    
    Yes, added some DEBUG output to this file


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183126183
  
    --- Diff: phoenix-core/src/it/java/org/apache/phoenix/end2end/join/HashJoinPersistentCacheIT.java ---
    @@ -0,0 +1,94 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + * http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.phoenix.end2end.join;
    +
    +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
    +import static org.junit.Assert.assertEquals;
    +
    +import java.sql.Connection;
    +import java.sql.DriverManager;
    +import java.sql.ResultSet;
    +import java.util.Properties;
    +
    +import org.apache.phoenix.end2end.join.HashJoinCacheIT.InvalidateHashCache;
    +import org.apache.phoenix.util.PropertiesUtil;
    +import org.apache.phoenix.util.SchemaUtil;
    +import org.apache.phoenix.util.TestUtil;
    +import org.junit.Test;
    +
    +public class HashJoinPersistentCacheIT extends BaseJoinIT {
    +
    +    @Override
    +    protected String getTableName(Connection conn, String virtualName) throws Exception {
    +        String realName = super.getTableName(conn, virtualName);
    +        TestUtil.addCoprocessor(conn, SchemaUtil.normalizeFullTableName(realName), InvalidateHashCache.class);
    +        return realName;
    +    }
    +                
    +    @Test
    +    public void testPersistentCache() throws Exception {
    +      Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    +      Connection conn = DriverManager.getConnection(getUrl(), props);
    +
    +      createTestTable(getUrl(), "CREATE TABLE IF NOT EXISTS states (state CHAR(2) NOT NULL, name VARCHAR NOT NULL CONSTRAINT my_pk PRIMARY KEY (state, name))");
    +      createTestTable(getUrl(), "CREATE TABLE IF NOT EXISTS cities (state CHAR(2) NOT NULL, city VARCHAR NOT NULL, population BIGINT CONSTRAINT my_pk PRIMARY KEY (state, city))");
    +
    +      conn.prepareStatement("UPSERT INTO states VALUES ('CA', 'California')").executeUpdate();
    +      conn.prepareStatement("UPSERT INTO states VALUES ('AZ', 'Arizona')").executeUpdate();
    +      conn.prepareStatement("UPSERT INTO cities VALUES ('CA', 'San Francisco', 50000)").executeUpdate();
    +      conn.prepareStatement("UPSERT INTO cities VALUES ('CA', 'Sacramento', 3000)").executeUpdate();
    +      conn.prepareStatement("UPSERT INTO cities VALUES ('AZ', 'Phoenix', 20000)").executeUpdate();
    +      conn.commit();
    +
    +      /* First, run query without using the persistent cache. This should return
    +       * different results after an UPSERT takes place.
    +       */
    +      ResultSet rs = conn.prepareStatement("SELECT SUM(population) FROM states s JOIN cities c ON c.state = s.state").executeQuery();
    +      rs.next();
    +      int population1 = rs.getInt(1);
    +
    +      conn.prepareStatement("UPSERT INTO cities VALUES ('CA', 'Mt View', 1500)").executeUpdate();
    +      conn.commit();
    +      rs = conn.prepareStatement("SELECT SUM(population) FROM states s JOIN cities c ON c.state = s.state").executeQuery();
    +      rs.next();
    +      int population2 = rs.getInt(1);
    +      
    +      assertEquals(73000, population1);
    +      assertEquals(74500, population2);
    +      
    +      /* Second, run query using the persistent cache. This should return the
    +       * same results after an UPSERT takes place.
    +       */
    +      rs = conn.prepareStatement("SELECT /*+ USE_PERSISTENT_CACHE */ SUM(population) FROM states s JOIN cities c ON c.state = s.state").executeQuery();
    +      rs.next();
    +      int population3 = rs.getInt(1);
    +
    +      conn.prepareStatement("UPSERT INTO cities VALUES ('CA', 'Palo Alto', 2000)").executeUpdate();
    +      conn.commit();
    +      rs = conn.prepareStatement("SELECT /*+ USE_PERSISTENT_CACHE */ SUM(population) FROM states s JOIN cities c ON c.state = s.state").executeQuery();
    +      rs.next();
    +      int population4 = rs.getInt(1);
    +      rs = conn.prepareStatement("SELECT SUM(population) FROM states s JOIN cities c ON c.state = s.state").executeQuery();
    +      rs.next();
    +      int population5 = rs.getInt(1);
    +      
    +      assertEquals(74500, population3);
    +      assertEquals(74500, population4);
    +      assertEquals(76500, population5);
    +    }
    +}
    --- End diff --
    
    Nice test. Since the persistent cache is supposed to be reusable across different queries, can we have another test in which the same cache is used for different queries?


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    > Another question to consider besides the suggested changes: do we need a SQL command to remove a specific cache entry and/or purge the entire persistent cache?
    
    I think that's a good idea but I would prefer to leave it for a future enhancement PR. There's a lot of improvements that can be made once people start using this and make feature requests. 


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211401005
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/HashJoinRegionScanner.java ---
    @@ -23,6 +23,7 @@
     import java.util.List;
     import java.util.Queue;
     
    +import org.apache.commons.codec.binary.Hex;
    --- End diff --
    
    Unused, remove it.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211783995
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    --- End diff --
    
    fixed


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by JamesRTaylor <gi...@git.apache.org>.
Github user JamesRTaylor commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    Is this ready to go, @ortutay? It looks pretty clean now.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r188778824
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/compile/QueryCompiler.java ---
    @@ -314,7 +314,8 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo
                         if (i < count - 1) {
                             fieldPositions[i + 1] = fieldPositions[i] + (tables[i] == null ? 0 : (tables[i].getColumns().size() - tables[i].getPKColumns().size()));
                         }
    -                    hashPlans[i] = new HashSubPlan(i, subPlans[i], optimized ? null : hashExpressions, joinSpec.isSingleValueOnly(), keyRangeLhsExpression, keyRangeRhsExpression);
    +                    boolean usePersistentCache = joinTable.getStatement().getHint().hasHint(Hint.USE_PERSISTENT_CACHE);
    --- End diff --
    
    Done


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183128249
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +153,164 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        return CacheBuilder.newBuilder()
    +            .expireAfterAccess(ttl, TimeUnit.MILLISECONDS)
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    --- End diff --
    
    Looks like the indentation is not right here. Can you perform a check through the entire PR?


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    Updated this to target `master`


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211397572
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    --- End diff --
    
    Is the iteration of `values()` threadsafe in the face of another thread updating the persistentServerCaches?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183135634
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java ---
    @@ -488,11 +502,20 @@ public ServerCache execute(HashJoinPlan parent) throws SQLException {
                 if (hashExpressions != null) {
                     ResultIterator iterator = plan.iterator();
                     try {
    -                    cache =
    -                            parent.hashClient.addHashCache(ranges, iterator,
    +                    final byte[] cacheId;
    +                    if (usePersistentCache) {
    --- End diff --
    
    Like I said in an earlier comment, if using persistent cache, we don't need to call "check" or "add" cache here, instead we catch a specific Exception and addServerCache at this point. Still, we might wanna return "null" if this is persistent cache so later on the cache "close" method won't be called by the HashJoinPlan clean-up routine.


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by dbwong <gi...@git.apache.org>.
Github user dbwong commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    Looks okay to me.  I spent a bit of time looking if there would be any issues for concurrent attempts to create the same sever side cache but I think everything should be fine along that path.


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by JamesRTaylor <gi...@git.apache.org>.
Github user JamesRTaylor commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    Looks really good to me. Nice work, @ortutay! Any further comments, @maryannxue?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r188783687
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +153,164 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        return CacheBuilder.newBuilder()
    +            .expireAfterAccess(ttl, TimeUnit.MILLISECONDS)
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    --- End diff --
    
    Fixed it here. FWIW some files mix tabs / spaces


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r188777161
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +153,164 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        return CacheBuilder.newBuilder()
    +            .expireAfterAccess(ttl, TimeUnit.MILLISECONDS)
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry maybeGet(ImmutableBytesPtr cacheId) {
    --- End diff --
    
    Done, also removed `maybeDemote`


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211400520
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    --- End diff --
    
    Can we get some DEBUG/TRACE logging here? History has told me that being able to understand evictions about server-side caches in Phoenix is very useful ;)


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183133375
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/compile/QueryCompiler.java ---
    @@ -314,7 +314,8 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo
                         if (i < count - 1) {
                             fieldPositions[i + 1] = fieldPositions[i] + (tables[i] == null ? 0 : (tables[i].getColumns().size() - tables[i].getPKColumns().size()));
                         }
    -                    hashPlans[i] = new HashSubPlan(i, subPlans[i], optimized ? null : hashExpressions, joinSpec.isSingleValueOnly(), keyRangeLhsExpression, keyRangeRhsExpression);
    +                    boolean usePersistentCache = joinTable.getStatement().getHint().hasHint(Hint.USE_PERSISTENT_CACHE);
    --- End diff --
    
    We can make "usePersistentCache" a member of QueryCompiler and initialize it in the beginning just like "noChildParentJoinOptimization".


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r188783472
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/compile/QueryCompiler.java ---
    @@ -383,7 +384,7 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo
                             new PTable[]{lhsTable}, new int[]{fieldPosition}, postJoinFilterExpression, QueryUtil.getOffsetLimit(limit, offset));
                     Pair<Expression, Expression> keyRangeExpressions = new Pair<Expression, Expression>(null, null);
                     getKeyExpressionCombinations(keyRangeExpressions, context, joinTable.getStatement(), rhsTableRef, type, joinExpressions, hashExpressions);
    -                return HashJoinPlan.create(joinTable.getStatement(), rhsPlan, joinInfo, new HashSubPlan[]{new HashSubPlan(0, lhsPlan, hashExpressions, false, keyRangeExpressions.getFirst(), keyRangeExpressions.getSecond())});
    +                return HashJoinPlan.create(joinTable.getStatement(), rhsPlan, joinInfo, new HashSubPlan[]{new HashSubPlan(0, lhsPlan, hashExpressions, false, false, keyRangeExpressions.getFirst(), keyRangeExpressions.getSecond())});
    --- End diff --
    
    @maryannxue I've changed the code here to use the `usePersistentCache` flag, but I'm not sure how to force a `HASH_BUILD_LEFT` strategy. The test I've put in the integration test file does not actually use that strategy. Do you know of an easy way to force a left table hash join?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211398424
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    --- End diff --
    
    I'm not getting how these `CacheEntries` are being sorted. It's based off of the `hits` member variable, right?
    
    So, the persistentCaches that have the least number of queries run against them we would remove first?
    
    Do we want to/are we able to include the size of the persistentCache in this decision?


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    > should I post a 4.x branch patch on the Jira ticket now?
    
    I don't have any more feedback for ya, so, as far as I'm concerned, you can work on a backport patch :)


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by twdsilva <gi...@git.apache.org>.
Github user twdsilva commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211414349
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    --- End diff --
    
    Does this try to evict from both persistent cache and the regular cache?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211400782
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/compile/QueryCompiler.java ---
    @@ -314,7 +316,8 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo
                         if (i < count - 1) {
                             fieldPositions[i + 1] = fieldPositions[i] + (tables[i] == null ? 0 : (tables[i].getColumns().size() - tables[i].getPKColumns().size()));
                         }
    -                    hashPlans[i] = new HashSubPlan(i, subPlans[i], optimized ? null : hashExpressions, joinSpec.isSingleValueOnly(), keyRangeLhsExpression, keyRangeRhsExpression);
    +//                    boolean usePersistentCache = joinTable.getStatement().getHint().hasHint(Hint.USE_PERSISTENT_CACHE);
    --- End diff --
    
    Remove it


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by twdsilva <gi...@git.apache.org>.
Github user twdsilva commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211414705
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        int size = cachePtr.getLength() + txState.length;
    +        if (size > available) {
    +            evictInactiveEntries(Math.max(size - available + EVICTION_MARGIN_BYTES, EVICTION_MARGIN_BYTES));
    +        }
    +        MemoryChunk chunk = this.getMemoryManager().allocate(size);
             boolean success = false;
             try {
    -            Closeable element = cacheFactory.newCache(cachePtr, txState, chunk, useProtoForIndexMaintainer, clientVersion);
    -            getServerCaches().put(cacheId, element);
    +            CacheEntry entry;
    +            synchronized(this) {
    +                entry = getIfPresent(cacheId);
    +                if (entry == null) {
    +                    entry = new CacheEntry(
    +                            cacheId, cachePtr, cacheFactory, txState, chunk,
    +                            usePersistentCache, useProtoForIndexMaintainer,
    +                            clientVersion);
    +                    getServerCaches().put(cacheId, entry);
    --- End diff --
    
    Do we need to put the entry in both the persistent cache and the regular cache?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211783411
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/ServerCacheClient.java ---
    @@ -336,6 +356,7 @@ private void removeServerCache(final ServerCache cache, Set<HRegionLocation> rem
                 ConnectionQueryServices services = connection.getQueryServices();
                 Throwable lastThrowable = null;
                 final PTable cacheUsingTable = cacheUsingTableMap.get(Bytes.mapKey(cacheId));
    +            cacheUsingTableMap.keySet();
    --- End diff --
    
    No, removed it


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by twdsilva <gi...@git.apache.org>.
Github user twdsilva commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211426819
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/iterate/TableResultIterator.java ---
    @@ -194,13 +194,10 @@ public Tuple next() throws SQLException {
                                 if (retry <= 0) {
                                     throw e1;
                                 }
    +                            Long cacheId = ((HashJoinCacheNotFoundException) e1).getCacheId();
                                 retry--;
                                 try {
    -                                Long cacheId = ((HashJoinCacheNotFoundException) e1).getCacheId();
    -
    -                                ServerCache cache = caches == null ? null :
    --- End diff --
    
    Do we not need this null check any more?


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    @joshelser should I post a 4.x branch patch on the Jira ticket now? Or wait until this is merged?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by dbwong <gi...@git.apache.org>.
Github user dbwong commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211429612
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/ServerCacheClient.java ---
    @@ -336,6 +356,7 @@ private void removeServerCache(final ServerCache cache, Set<HRegionLocation> rem
                 ConnectionQueryServices services = connection.getQueryServices();
                 Throwable lastThrowable = null;
                 final PTable cacheUsingTable = cacheUsingTableMap.get(Bytes.mapKey(cacheId));
    +            cacheUsingTableMap.keySet();
    --- End diff --
    
    Does this do anything?


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    Sounds good, also squashed the commits just now


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    Ok, submitted the master (5.x) patch just now, can folllow-up with the 4.x patch after 5.x looks good / is merged


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183130270
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +153,164 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        return CacheBuilder.newBuilder()
    +            .expireAfterAccess(ttl, TimeUnit.MILLISECONDS)
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry maybeGet(ImmutableBytesPtr cacheId) {
    +        maybePromote(cacheId);
    +        CacheEntry entry = getServerCaches().getIfPresent(cacheId);
    +        return entry;
    +    }
    +
    +    private void maybePromote(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry == null) {
    +            return;
    +        }
    +        getServerCaches().put(cacheId, entry);
    +    }
    +    
    +    private void maybeDemote(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getServerCaches().getIfPresent(cacheId);
    +        if (entry == null) {
    +            return;
    +        }
    +        entry.decrementLiveQueryCount();
    +        if (!entry.isLive()) {
    +            getServerCaches().invalidate(cacheId);
    +        }
    +    }
    +    
    +    public void debugPrintCaches() {
    +		System.out.println("Live cache:" + getServerCaches());
    +		for (ImmutableBytesPtr key : getServerCaches().asMap().keySet()) {
    +			System.out.println("- " + Hex.encodeHexString(key.get()) +
    +					" -> " + getServerCaches().getIfPresent(key).size +
    +					" lq:" + getServerCaches().getIfPresent(key).liveQueriesCount +
    +					" " + Hex.encodeHexString(getServerCaches().getIfPresent(key).cachePtr.get()));
    +		}
    +		System.out.println("Persistent cache:" + getPersistentServerCaches());
    +		for (ImmutableBytesPtr key : getPersistentServerCaches().asMap().keySet()) {
    +			System.out.println("- " + Hex.encodeHexString(key.get()) +
    +					" -> " + getPersistentServerCaches().getIfPresent(key).size +
    +					" " + Hex.encodeHexString(getPersistentServerCaches().getIfPresent(key).cachePtr.get()));
    +		}
    +	}
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = maybeGet(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
         
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public boolean checkServerCache(ImmutableBytesPtr cacheId, boolean shouldIncrementLiveQueryCount) {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        CacheEntry entry = maybeGet(cacheId);
    +        if (entry != null && shouldIncrementLiveQueryCount) {
    +        	entry.incrementLiveQueryCount();
    +        }
    +		return entry != null;
    +    }
    +    
    +    @Override
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
    +        getServerCaches().cleanUp();
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        int size = cachePtr.getLength() + txState.length;
    +        if (size > available) {
    +            evictInactiveEntries(Math.max(size - available + EVICTION_MARGIN_BYTES, EVICTION_MARGIN_BYTES));
    +        }
    +        MemoryChunk chunk = this.getMemoryManager().allocate(size);
             boolean success = false;
             try {
    -            Closeable element = cacheFactory.newCache(cachePtr, txState, chunk, useProtoForIndexMaintainer, clientVersion);
    -            getServerCaches().put(cacheId, element);
    +            CacheEntry entry;
    +            synchronized(this) {
    +                entry = maybeGet(cacheId);
    +                if (entry == null) {
    +                    entry = new CacheEntry(
    +                            cacheId, cachePtr, cacheFactory, txState, chunk,
    +                            usePersistentCache, useProtoForIndexMaintainer,
    +                            clientVersion);
    +                    getServerCaches().put(cacheId, entry);
    +                    available = this.getMemoryManager().getAvailableMemory();
    +                    if (usePersistentCache) {
    +                        getPersistentServerCaches().put(cacheId, entry);
    +                    }
    +                }
    +                entry.incrementLiveQueryCount();
    +            }
                 success = true;
    -            return element;
    +            return entry;
             } finally {
                 if (!success) {
                     Closeables.closeAllQuietly(Collections.singletonList(chunk));
                 }
    -        }           
    +        }
         }
    -    
    +
         @Override
    -    public void removeServerCache(ImmutableBytesPtr cacheId) {
    -        getServerCaches().invalidate(cacheId);
    +    synchronized public void removeServerCache(ImmutableBytesPtr cacheId) {
    --- End diff --
    
    Is there any reason why we need to "demote" the cache instead of invalidating it here?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211403555
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    --- End diff --
    
    Two scary points (that I hope I just missed via my scanning):
    
    * I don't see a corresponding update to the GlobalMemoryManager. Are we accounting for the size of `persistentServerCaches` somewhere else?
    * Do users who execute queries with persistentCaches have the ability to deny the queries of users not running persistentCaches (by saturating the total RS's serverCache). The 30min default timeout to start evicting persistentCaches makes me worry as that's a long time.


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    Submitted patch for 4.x, I can't find a way to submit the patch for 5.x in the same Jira ticket. It's the diff from this PR though: https://patch-diff.githubusercontent.com/raw/apache/phoenix/pull/298.patch



---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211785713
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java ---
    @@ -241,8 +251,35 @@ public TaskExecutionMetricsHolder getTaskExecutionMetric() {
             if (statement.getInnerSelectStatement() != null && postFilter != null) {
                 iterator = new FilterResultIterator(iterator, postFilter);
             }
    -        
    -        return iterator;
    +
    +        if (hasSubPlansWithPersistentCache) {
    +            return peekForPersistentCache(iterator, scanGrouper, scan);
    +        } else {
    +            return iterator;
    +        }
    +    }
    +
    +    private ResultIterator peekForPersistentCache(ResultIterator iterator, ParallelScanGrouper scanGrouper, Scan scan) throws SQLException {
    --- End diff --
    
    It is not explicitly tested, however it is tested from `HashJoinPersistentCacheIT`. Basically, this code path handles the first, optimistic query which assumes the cache already exists, and then does the second query which generates the cache. It only does the second one when needed.
    
    The rethrow for this part:
    
    ```                if (delegate.getContext().getDisablePersistentCache(cacheId)) {
                        throw e2;
                    }
    ``` is not tested, I think


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784863
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/join/HashCacheFactory.java ---
    @@ -25,18 +25,22 @@
     import java.io.IOException;
     import java.sql.SQLException;
     import java.util.ArrayList;
    +import java.util.Arrays;
     import java.util.Collections;
     import java.util.HashMap;
     import java.util.LinkedList;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import net.jcip.annotations.Immutable;
     
    +import org.apache.commons.codec.binary.Hex;
    --- End diff --
    
    done


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r188778970
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/memory/GlobalMemoryManager.java ---
    @@ -159,6 +161,10 @@ protected void finalize() throws Throwable {
             }
     
             private void freeMemory() {
    +//        	System.out.println("Free memory! " + size);
    --- End diff --
    
    Done


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    @JamesRTaylor @maryannxue updated for all comments in the PR ; this now uses an exception flow for checking for presence of SQ cache, instead of the previous RPC approach. I also a dded to the integration test to verify that the SQ cache is properly used across queries.
    
    Also, regarding expiring the cache--we have been using a technique internally for this based on nonces. You can add a no-op condition to the query such as "1=1" or "2=2" which changes the persistent cache key, and thus is a way to force cache invalidation. You can do it on a daily basis, eg. 20180731=20180731, and this can also be used to pre-warm caches for upcoming days as well. I'm planning to make a blog post explaining SQ cache + how to rotate nonces once this change has been merged.


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    @dbwong @twdsilva  any comments? is this ready to merge?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183128592
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +153,164 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        return CacheBuilder.newBuilder()
    +            .expireAfterAccess(ttl, TimeUnit.MILLISECONDS)
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry maybeGet(ImmutableBytesPtr cacheId) {
    --- End diff --
    
    Think we can just call it "get" or "getIfPresent" and merge {{maybePromote}} into this call.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211401373
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java ---
    @@ -494,19 +540,37 @@ public ServerCache execute(HashJoinPlan parent) throws SQLException {
                 if (hashExpressions != null) {
                     ResultIterator iterator = plan.iterator();
                     try {
    -                    cache =
    -                            parent.hashClient.addHashCache(ranges, iterator,
    -                                plan.getEstimatedSize(), hashExpressions, singleValueOnly,
    +                    final byte[] cacheId;
    +                    String queryString = plan.getStatement().toString().replaceAll("\\$[0-9]+", "\\$");
    +                    if (usePersistentCache) {
    +                        cacheId = Arrays.copyOfRange(digest.digest(queryString.getBytes()), 0, 8);
    +                        boolean disablePersistentCache = parent.delegate.getContext().getDisablePersistentCache(Bytes.toLong(cacheId));
    +                        if (!disablePersistentCache) {
    +                            try {
    +                                cache = parent.hashClient.createServerCache(cacheId, parent.delegate);
    +                            } catch (IOException e) {
    +                                throw new RuntimeException(e);
    +                            }
    +                        }
    +                    } else {
    +                        cacheId = Bytes.toBytes(RANDOM.nextLong());
    +                    }
    +                    System.out.println("Using cache ID " + Hex.encodeHexString(cacheId) + " for " + queryString);
    --- End diff --
    
    This, and others, need to use a logger.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211783956
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    --- End diff --
    
    Good point, added `synchronized` to this method.
    
    The filtering for `!isAlive()` was below, but I've changed to behavior as a bit. Now, nothing that "isAlive" exists in `getPersistentServerCaches()`, so the filter is not necessary.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211992643
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    --- End diff --
    
    thanks!


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784526
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/coprocessor/HashJoinRegionScanner.java ---
    @@ -23,6 +23,7 @@
     import java.util.List;
     import java.util.Queue;
     
    +import org.apache.commons.codec.binary.Hex;
    --- End diff --
    
    done


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784448
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        int size = cachePtr.getLength() + txState.length;
    +        if (size > available) {
    +            evictInactiveEntries(Math.max(size - available + EVICTION_MARGIN_BYTES, EVICTION_MARGIN_BYTES));
    +        }
    +        MemoryChunk chunk = this.getMemoryManager().allocate(size);
             boolean success = false;
             try {
    -            Closeable element = cacheFactory.newCache(cachePtr, txState, chunk, useProtoForIndexMaintainer, clientVersion);
    -            getServerCaches().put(cacheId, element);
    +            CacheEntry entry;
    +            synchronized(this) {
    +                entry = getIfPresent(cacheId);
    +                if (entry == null) {
    +                    entry = new CacheEntry(
    +                            cacheId, cachePtr, cacheFactory, txState, chunk,
    +                            usePersistentCache, useProtoForIndexMaintainer,
    +                            clientVersion);
    +                    getServerCaches().put(cacheId, entry);
    --- End diff --
    
    Yes, if `usePersistentCache` is true, it will be added on the following line


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211401617
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/memory/GlobalMemoryManager.java ---
    @@ -17,6 +17,8 @@
      */
     package org.apache.phoenix.memory;
     
    +import java.util.Arrays;
    --- End diff --
    
    Remove


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by twdsilva <gi...@git.apache.org>.
Github user twdsilva commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211412318
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        int size = cachePtr.getLength() + txState.length;
    +        if (size > available) {
    +            evictInactiveEntries(Math.max(size - available + EVICTION_MARGIN_BYTES, EVICTION_MARGIN_BYTES));
    --- End diff --
    
    Seems like this will always be size - available + EVICTION_MARGIN_BYTES since size>available. So if we need to evict we will evict a minimum of EVICTION_MARGIN_BYTES ?


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by joshelser <gi...@git.apache.org>.
Github user joshelser commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211403791
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    --- End diff --
    
    I am fairly certain that we export serverCache metrics to the HBase RS metrics subsystem. Assuming that we do, can we break out the persistentServerCache usage as well? That would be nice to monitor.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784471
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/compile/QueryCompiler.java ---
    @@ -314,7 +316,8 @@ protected QueryPlan compileJoinQuery(JoinCompiler.Strategy strategy, StatementCo
                         if (i < count - 1) {
                             fieldPositions[i + 1] = fieldPositions[i] + (tables[i] == null ? 0 : (tables[i].getColumns().size() - tables[i].getPKColumns().size()));
                         }
    -                    hashPlans[i] = new HashSubPlan(i, subPlans[i], optimized ? null : hashExpressions, joinSpec.isSingleValueOnly(), keyRangeLhsExpression, keyRangeRhsExpression);
    +//                    boolean usePersistentCache = joinTable.getStatement().getHint().hasHint(Hint.USE_PERSISTENT_CACHE);
    --- End diff --
    
    done


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by twdsilva <gi...@git.apache.org>.
Github user twdsilva commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    If you upload a patch file without any branch name the precommit build uses master by default.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by JamesRTaylor <gi...@git.apache.org>.
Github user JamesRTaylor commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r187393698
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/ServerCacheClient.java ---
    @@ -216,22 +234,146 @@ public void close() throws SQLException {
                     }
                 }
             }
    -        
    +    }
    +    
    +    public ServerCache checkServerCache(final byte[] cacheId, ScanRanges keyRanges, final TableRef cacheUsingTableRef,
    --- End diff --
    
    FYI, we already have a mechanism for this. If the server throws a HashJoinCacheNotFoundException, then the client will react by sending the hash cache to the region servers that don't have it.


---

[GitHub] phoenix issue #298: PHOENIX-4666 Persistent subquery cache for hash joins

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on the issue:

    https://github.com/apache/phoenix/pull/298
  
    @JamesRTaylor almost ready, we've been testing/deploying this internally and have a few small changes that I'll push out before it's ready to merge


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784312
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    +        long available = this.getMemoryManager().getAvailableMemory();
    +        for (int i = 0; i < entries.length && available < bytesNeeded; i++) {
    +            CacheEntry entry = entries[i];
    +            if (!entry.isLive()) {
    +            	getServerCaches().invalidate(entry.getCacheId());
    +            	getPersistentServerCaches().invalidate(entry.getCacheId());
    +                available = this.getMemoryManager().getAvailableMemory();
    +            }
    +        }
    +    }
    +
    +    private CacheEntry getIfPresent(ImmutableBytesPtr cacheId) {
    +        CacheEntry entry = getPersistentServerCaches().getIfPresent(cacheId);
    +        if (entry != null) {
    +            getServerCaches().put(cacheId, entry);
    +        }return getServerCaches().getIfPresent(cacheId);
    +    }
    +
    +	@Override
         public Closeable getServerCache(ImmutableBytesPtr cacheId) {
             getServerCaches().cleanUp();
    -        return getServerCaches().getIfPresent(cacheId);
    +        CacheEntry entry = getIfPresent(cacheId);
    +        if (entry == null) {
    +            return null;
    +        }
    +        return entry.closeable;
         }
    -    
    +
         @Override
    -    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, int clientVersion) throws SQLException {
    +    public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException {
             getServerCaches().cleanUp();
    -        MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    +        long available = this.getMemoryManager().getAvailableMemory();
    --- End diff --
    
    > I don't see a corresponding update to the GlobalMemoryManager. Are we accounting for the size of persistentServerCaches somewhere else?
    
    I think this is handled, but I could be wrong. There is a call like this: `MemoryChunk chunk = this.getMemoryManager().allocate(size);`. This allocates the server cache. The server cache can then live in one or two hash maps, either only `getServerCaches()`, or both `getServerCaches()` and `getPersistentServerCaches()`. However, even if it lives in both, it only uses `size` bytes, since the two maps have a pointer to the same memory chunk.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by maryannxue <gi...@git.apache.org>.
Github user maryannxue commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r183136068
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/memory/GlobalMemoryManager.java ---
    @@ -159,6 +161,10 @@ protected void finalize() throws Throwable {
             }
     
             private void freeMemory() {
    +//        	System.out.println("Free memory! " + size);
    --- End diff --
    
    I think this a mistake, missed from your code clean-up.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211783639
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/cache/TenantCacheImpl.java ---
    @@ -77,57 +152,132 @@ public MemoryManager getMemoryManager() {
             return memoryManager;
         }
     
    -    private Cache<ImmutableBytesPtr,Closeable> getServerCaches() {
    +    private Cache<ImmutableBytesPtr,CacheEntry> getServerCaches() {
             /* Delay creation of this map until it's needed */
             if (serverCaches == null) {
                 synchronized(this) {
                     if (serverCaches == null) {
    -                    serverCaches = CacheBuilder.newBuilder()
    -                        .expireAfterAccess(maxTimeToLiveMs, TimeUnit.MILLISECONDS)
    -                        .ticker(getTicker())
    -                        .removalListener(new RemovalListener<ImmutableBytesPtr, Closeable>(){
    -                            @Override
    -                            public void onRemoval(RemovalNotification<ImmutableBytesPtr, Closeable> notification) {
    -                                Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    -                            }
    -                        })
    -                        .build();
    +                    serverCaches = buildCache(maxTimeToLiveMs, false);
                     }
                 }
             }
             return serverCaches;
         }
    +
    +    private Cache<ImmutableBytesPtr,CacheEntry> getPersistentServerCaches() {
    +        /* Delay creation of this map until it's needed */
    +        if (persistentServerCaches == null) {
    +            synchronized(this) {
    +                if (persistentServerCaches == null) {
    +                    persistentServerCaches = buildCache(maxPersistenceTimeToLiveMs, true);
    +                }
    +            }
    +        }
    +        return persistentServerCaches;
    +    }
    +
    +    private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    +        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    +        if (isPersistent) {
    +            builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    +        } else {
    +            builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    +        }
    +        return builder
    +            .ticker(getTicker())
    +            .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
    +                @Override
    +                public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
    +                	if (isPersistent || !notification.getValue().getUsePersistentCache()) {
    +                        Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
    +                	}
    +                }
    +            })
    +            .build();
    +    }
         
    -    @Override
    +    private void evictInactiveEntries(long bytesNeeded) {
    +        CacheEntry[] entries = getPersistentServerCaches().asMap().values().toArray(new CacheEntry[]{});
    +        Arrays.sort(entries);
    --- End diff --
    
    Yes, it's currently just based on `hits`, which is not very smart, but very simple to code.
    
    I think it should, at least, account for how long the entry has been in the cache, and perhaps take other things into account, like size of the cache entry. I was going to submit a follow-up PR to improve the ranking.


---

[GitHub] phoenix pull request #298: PHOENIX-4666 Persistent subquery cache for hash j...

Posted by ortutay <gi...@git.apache.org>.
Github user ortutay commented on a diff in the pull request:

    https://github.com/apache/phoenix/pull/298#discussion_r211784739
  
    --- Diff: phoenix-core/src/main/java/org/apache/phoenix/execute/HashJoinPlan.java ---
    @@ -494,19 +540,37 @@ public ServerCache execute(HashJoinPlan parent) throws SQLException {
                 if (hashExpressions != null) {
                     ResultIterator iterator = plan.iterator();
                     try {
    -                    cache =
    -                            parent.hashClient.addHashCache(ranges, iterator,
    -                                plan.getEstimatedSize(), hashExpressions, singleValueOnly,
    +                    final byte[] cacheId;
    +                    String queryString = plan.getStatement().toString().replaceAll("\\$[0-9]+", "\\$");
    +                    if (usePersistentCache) {
    +                        cacheId = Arrays.copyOfRange(digest.digest(queryString.getBytes()), 0, 8);
    +                        boolean disablePersistentCache = parent.delegate.getContext().getDisablePersistentCache(Bytes.toLong(cacheId));
    +                        if (!disablePersistentCache) {
    +                            try {
    +                                cache = parent.hashClient.createServerCache(cacheId, parent.delegate);
    +                            } catch (IOException e) {
    +                                throw new RuntimeException(e);
    +                            }
    +                        }
    +                    } else {
    +                        cacheId = Bytes.toBytes(RANDOM.nextLong());
    +                    }
    +                    System.out.println("Using cache ID " + Hex.encodeHexString(cacheId) + " for " + queryString);
    +                    if (cache == null) {
    --- End diff --
    
    yes. the naming for `disablePersistentCache` not great, maybe I should change it. That variable is true on a retry. It retries when the persistent cache was missing on the first pass, so now it is effectively warming the cache that will be used in subsequent queries.
    
    Maybe `isPersistentCacheRetry` would be a better variable name here.


---