DfsPackFile: Account for offset64 in PackIndex cache size

DfsPackFile estimated the cached memory size of a PackIndex as
(OBJECT_ID_LENGTH + 8) * getObjectCount(), omitting
PackIndexV2#offset64 (8 bytes per object at pack offset >= 2 GiB). In
repositories with large packfiles where most objects reside past 2 GiB,
this reports 28 bytes instead of 36 bytes per v2 index entry to
DfsBlockCache.

Add PackIndex#getMemorySize() with overrides in PackIndexV1 (24 bytes
per object) and PackIndexV2 (28 bytes per object plus offset64.length),
and use it in DfsPackFile#loadPackIndex and DfsPackFile#setPackIndex.

Change-Id: Ic9c964b727817100a1fe52c7e2312bdaac02a774
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsPackFileTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsPackFileTest.java
index 54c8e5d..1a434d4 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsPackFileTest.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsPackFileTest.java
@@ -20,16 +20,22 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
+import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.zip.Deflater;
 
 import org.eclipse.jgit.internal.storage.commitgraph.CommitGraph;
 import org.eclipse.jgit.internal.storage.dfs.DfsObjDatabase.PackSource;
 import org.eclipse.jgit.internal.storage.dfs.DfsReader.PackLoadListener;
+import org.eclipse.jgit.internal.storage.file.BasePackIndexWriter;
 import org.eclipse.jgit.internal.storage.file.PackBitmapIndex;
+import org.eclipse.jgit.internal.storage.file.PackIndex;
 import org.eclipse.jgit.internal.storage.pack.PackExt;
 import org.eclipse.jgit.internal.storage.pack.PackOutputStream;
 import org.eclipse.jgit.internal.storage.pack.PackWriter;
@@ -42,6 +48,7 @@
 import org.eclipse.jgit.lib.ObjectId;
 import org.eclipse.jgit.revwalk.RevWalk;
 import org.eclipse.jgit.storage.pack.PackConfig;
+import org.eclipse.jgit.transport.PackedObjectInfo;
 import org.eclipse.jgit.transport.ReceiveCommand;
 import org.junit.Before;
 import org.junit.Test;
@@ -320,6 +327,83 @@ public void testCommitGraphInBlockCacheMatchReadChangedPathsFlagState()
 		assertNotNull(cgWithCpfAgain.getChangedPathFilter(0));
 	}
 
+	@Test
+	public void testPackIndexCacheSizeAccountsForOffset64OnLoad()
+			throws IOException {
+		DfsBlockCache.reconfigure(new DfsBlockCacheConfig().setBlockSize(512)
+				.setBlockLimit(512 * 100));
+
+		byte[] idxBytes = createV2IndexWithOffset64();
+		DfsPackDescription desc = db.getObjectDatabase().newPack(PackSource.GC);
+		try (DfsOutputStream out = db.getObjectDatabase().writeFile(desc,
+				PackExt.INDEX)) {
+			out.write(idxBytes);
+		}
+		desc.addFileExt(PackExt.PACK);
+		desc.addFileExt(PackExt.INDEX);
+		desc.setFileSize(PackExt.INDEX, idxBytes.length);
+		desc.setObjectCount(3);
+		db.getObjectDatabase().commitPack(Collections.singletonList(desc),
+				null);
+
+		try (DfsReader reader = db.getObjectDatabase().newReader()) {
+			DfsPackFile pack = db.getObjectDatabase().getPacks()[0];
+			PackIndex idx = pack.getPackIndex(reader);
+			long expectedSize = 3L * (Constants.OBJECT_ID_LENGTH + 8L)
+					+ 2L * 8L;
+			assertEquals(expectedSize, idx.getMemorySize());
+			assertEquals(expectedSize, DfsBlockCache.getInstance()
+					.getCurrentSize()[PackExt.INDEX.getPosition()]);
+		}
+	}
+
+	@Test
+	public void testSetPackIndexCacheSizeAccountsForOffset64()
+			throws IOException {
+		DfsBlockCache.reconfigure(new DfsBlockCacheConfig().setBlockSize(512)
+				.setBlockLimit(512 * 100));
+
+		byte[] idxBytes = createV2IndexWithOffset64();
+		PackIndex idx = PackIndex.read(new ByteArrayInputStream(idxBytes));
+
+		DfsPackDescription desc = db.getObjectDatabase()
+				.newPack(PackSource.INSERT);
+		desc.addFileExt(PackExt.PACK);
+		desc.addFileExt(PackExt.INDEX);
+		db.getObjectDatabase().commitPack(Collections.singletonList(desc),
+				null);
+
+		DfsPackFile pack = db.getObjectDatabase().getPacks()[0];
+		pack.setPackIndex(idx);
+
+		long expectedSize = 3L * (Constants.OBJECT_ID_LENGTH + 8L) + 2L * 8L;
+		assertEquals(expectedSize, idx.getMemorySize());
+		assertEquals(expectedSize, DfsBlockCache.getInstance()
+				.getCurrentSize()[PackExt.INDEX.getPosition()]);
+	}
+
+	private static byte[] createV2IndexWithOffset64() throws IOException {
+		List<PackedObjectInfo> entries = new ArrayList<>();
+		PackedObjectInfo o1 = new PackedObjectInfo(ObjectId
+				.fromString("0000000000000000000000000000000000000001"));
+		o1.setOffset(12L);
+		entries.add(o1);
+		PackedObjectInfo o2 = new PackedObjectInfo(ObjectId
+				.fromString("8000000000000000000000000000000000000002"));
+		o2.setOffset(0x80000000L);
+		entries.add(o2);
+		PackedObjectInfo o3 = new PackedObjectInfo(ObjectId
+				.fromString("ff00000000000000000000000000000000000003"));
+		o3.setOffset(10L * (1L << 30));
+		entries.add(o3);
+		Collections.sort(entries);
+
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		BasePackIndexWriter.createVersion(out, 2).write(entries,
+				new byte[Constants.OBJECT_ID_LENGTH]);
+		return out.toByteArray();
+	}
+
 	private ObjectId setupPack(int bs, int ps) throws IOException {
 		DfsBlockCacheConfig cfg = new DfsBlockCacheConfig().setBlockSize(bs)
 				.setBlockLimit(bs * 100).setStreamRatio(bypassCache ? 0F : 1F);
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV1Test.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV1Test.java
index c4f6372..8fb2e32 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV1Test.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV1Test.java
@@ -12,14 +12,23 @@
 
 package org.eclipse.jgit.internal.storage.file;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.fail;
 
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
 
 import org.eclipse.jgit.errors.MissingObjectException;
 import org.eclipse.jgit.junit.JGitTestUtil;
+import org.eclipse.jgit.lib.Constants;
 import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.transport.PackedObjectInfo;
 import org.junit.Test;
 
 public class PackIndexV1Test extends PackIndexTestCase {
@@ -57,4 +66,34 @@ public void testCRC32() throws MissingObjectException {
 			// expected
 		}
 	}
+
+	@Test
+	public void testMemorySize() throws IOException {
+		assertEquals(8, smallIdx.getObjectCount());
+		assertEquals(8L * (Constants.OBJECT_ID_LENGTH + 4L),
+				smallIdx.getMemorySize());
+
+		List<PackedObjectInfo> entries = new ArrayList<>();
+		PackedObjectInfo small = new PackedObjectInfo(ObjectId
+				.fromString("0000000000000000000000000000000000000001"));
+		small.setOffset(12L);
+		entries.add(small);
+		PackedObjectInfo over2GiB = new PackedObjectInfo(ObjectId
+				.fromString("8000000000000000000000000000000000000002"));
+		over2GiB.setOffset(0x80000000L);
+		entries.add(over2GiB);
+		Collections.sort(entries);
+
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		BasePackIndexWriter.createVersion(out, 1).write(entries,
+				new byte[Constants.OBJECT_ID_LENGTH]);
+		PackIndex idx = PackIndex
+				.read(new ByteArrayInputStream(out.toByteArray()));
+
+		// V1 stores 32-bit unsigned offsets inline without offset64.
+		assertEquals(2, idx.getObjectCount());
+		assertEquals(1, idx.getOffset64Count());
+		assertEquals(2L * (Constants.OBJECT_ID_LENGTH + 4L),
+				idx.getMemorySize());
+	}
 }
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV2Test.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV2Test.java
index 1d179ab..c59a6fa 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV2Test.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackIndexV2Test.java
@@ -15,11 +15,19 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
 
 import org.eclipse.jgit.errors.MissingObjectException;
 import org.eclipse.jgit.junit.JGitTestUtil;
+import org.eclipse.jgit.lib.Constants;
 import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.transport.PackedObjectInfo;
 import org.junit.Test;
 
 public class PackIndexV2Test extends PackIndexTestCase {
@@ -68,4 +76,43 @@ public void testCRC32() throws MissingObjectException,
 		assertEquals(0x000000000B3B5BA6L, smallIdx.findCRC32(ObjectId
 				.fromString("c59759f143fb1fe21c197981df75a7ee00290799")));
 	}
+
+	@Test
+	public void testMemorySizeWithoutOffset64() {
+		assertEquals(8, smallIdx.getObjectCount());
+		assertEquals(0, smallIdx.getOffset64Count());
+		assertEquals(8L * (Constants.OBJECT_ID_LENGTH + 8L),
+				smallIdx.getMemorySize());
+	}
+
+	@Test
+	public void testMemorySizeWithOffset64() throws IOException {
+		List<PackedObjectInfo> entries = new ArrayList<>();
+		entries.add(objectWithOffset("0000000000000000000000000000000000000001",
+				12L));
+		entries.add(objectWithOffset("0000000000000000000000000000000000000002",
+				0x7fffffffL));
+		entries.add(objectWithOffset("8000000000000000000000000000000000000003",
+				0x80000000L));
+		entries.add(objectWithOffset("ff00000000000000000000000000000000000004",
+				10L * (1L << 30)));
+		Collections.sort(entries);
+
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		BasePackIndexWriter.createVersion(out, 2).write(entries,
+				new byte[Constants.OBJECT_ID_LENGTH]);
+		PackIndex idx = PackIndex
+				.read(new ByteArrayInputStream(out.toByteArray()));
+
+		assertEquals(4, idx.getObjectCount());
+		assertEquals(2, idx.getOffset64Count());
+		assertEquals(4L * (Constants.OBJECT_ID_LENGTH + 8L) + 2L * 8L,
+				idx.getMemorySize());
+	}
+
+	private static PackedObjectInfo objectWithOffset(String sha1, long offset) {
+		PackedObjectInfo info = new PackedObjectInfo(ObjectId.fromString(sha1));
+		info.setOffset(offset);
+		return info;
+	}
 }
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
index 4758f7a..36a989f 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
@@ -76,8 +76,6 @@
  * objects are similar.
  */
 public sealed class DfsPackFile extends BlockBasedFile permits DfsPackFileMidx {
-	private static final int REC_SIZE = Constants.OBJECT_ID_LENGTH + 8;
-
 	private static final long REF_POSITION = 0;
 
 	/**
@@ -234,10 +232,7 @@ public boolean isIndexLoaded() {
 	}
 
 	void setPackIndex(PackIndex idx) {
-		long objCnt = idx.getObjectCount();
-		int recSize = Constants.OBJECT_ID_LENGTH + 8;
-		long sz = objCnt * recSize;
-		cache.putRef(desc.getStreamKey(INDEX), sz, idx);
+		cache.putRef(desc.getStreamKey(INDEX), idx.getMemorySize(), idx);
 		index = idx;
 	}
 
@@ -1663,8 +1658,7 @@ private static RefWithSize<PackIndex> loadPackIndex(DfsReader ctx,
 				try (ReadableChannel rc = ctx.db.openFile(desc, INDEX)) {
 					PackIndex idx = PackIndex.read(alignTo8kBlocks(rc));
 					ctx.stats.readIdxBytes += rc.position();
-					return new RefWithSize<>(idx,
-							idx.getObjectCount() * REC_SIZE);
+					return new RefWithSize<>(idx, idx.getMemorySize());
 				} finally {
 					ctx.stats.readIdxMicros += elapsedMicros(start);
 				}
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndex.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndex.java
index b3e4efb..1ed71d1 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndex.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndex.java
@@ -25,6 +25,7 @@
 import org.eclipse.jgit.internal.JGitText;
 import org.eclipse.jgit.lib.AbbreviatedObjectId;
 import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.Constants;
 import org.eclipse.jgit.lib.MutableObjectId;
 import org.eclipse.jgit.lib.ObjectId;
 import org.eclipse.jgit.lib.ObjectIdSet;
@@ -297,6 +298,16 @@ void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
 	byte[] getChecksum();
 
 	/**
+	 * Estimate the size of the in-memory representation of this index.
+	 *
+	 * @return estimated size of this pack index in memory, in bytes
+	 */
+	default long getMemorySize() {
+		return (Constants.OBJECT_ID_LENGTH + 8L) * getObjectCount()
+				+ 8L * getOffset64Count();
+	}
+
+	/**
 	 * Represent mutable entry of pack index consisting of object id and offset
 	 * in pack (both mutable).
 	 *
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV1.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV1.java
index be48358..b5bc0a2 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV1.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV1.java
@@ -246,6 +246,11 @@ private static int idOffset(int mid) {
 		return packChecksum;
 	}
 
+	@Override
+	public long getMemorySize() {
+		return RECORD_SIZE * objectCnt;
+	}
+
 	private static class EntriesIteratorV1 extends EntriesIterator {
 		private int levelOne;
 
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV2.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV2.java
index 36e54fc..19d796c 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV2.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackIndexV2.java
@@ -289,6 +289,11 @@ else if (cmp == 0) {
 		return packChecksum;
 	}
 
+	@Override
+	public long getMemorySize() {
+		return (Constants.OBJECT_ID_LENGTH + 8L) * objectCnt + offset64.length;
+	}
+
 	private static class EntriesIteratorV2 extends EntriesIterator {
 		private int levelOne = 0;