You are viewing a plain text version of this content. The canonical link for it is here.
Posted to oak-commits@jackrabbit.apache.org by mr...@apache.org on 2015/01/13 16:52:07 UTC

svn commit: r1651391 - in /jackrabbit/oak/branches/1.0: ./ oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/ oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/ oak-core/src/main/java/org/apache/jackrabbit/oak/plug...

Author: mreutegg
Date: Tue Jan 13 15:52:07 2015
New Revision: 1651391

URL: http://svn.apache.org/r1651391
Log:
OAK-1791: Clean up dangling references to previous documents

Merged revisions 1650239, 1651323 and 1651382 from trunk

Added:
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitDocumentCleanUp.java
      - copied unchanged from r1651323, jackrabbit/oak/trunk/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitDocumentCleanUp.java
    jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/VersionGCWithSplitTest.java
      - copied unchanged from r1651323, jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/VersionGCWithSplitTest.java
Modified:
    jackrabbit/oak/branches/1.0/   (props changed)
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentMK.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitOperations.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGCSupport.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollector.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoVersionGCSupport.java
    jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java
    jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollectorTest.java
    jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/util/UtilsTest.java

Propchange: jackrabbit/oak/branches/1.0/
------------------------------------------------------------------------------
--- svn:mergeinfo (original)
+++ svn:mergeinfo Tue Jan 13 15:52:07 2015
@@ -1,2 +1,2 @@
-/jackrabbit/oak/trunk:1584578,1584602,1584614,1584616,1584709,1584781,1584937,1585297,1585304-1585305,1585420,1585424,1585427,1585448,1585465,1585468,1585486,1585497,1585509,1585647,1585655-1585656,1585661,1585665-1585666,1585669-1585670,1585673,1585680,1585719,1585763,1585770,1585896,1585904,1585907,1585940,1585949,1585951,1585956,1585962-1585963,1586287,1586320,1586364,1586372,1586655,1586836,1587130,1587224,1587399,1587408,1587472,1587485,1587488,1587538,1587580,1587807,1588033,1588042,1588046,1588066,1588201,1589025,1589101,1589137,1589141,1589263,1589440,1589442,1589484,1589488,1589661,1589664,1589682,1589708,1589741,1589748,1589789,1589794,1589850,1589864,1590628,1590660,1590684,1590697,1590701,1590980,1590988,1591101,1591226,1591229,1591293,1591314,1591317,1591362,1591374,1591381,1591438,1591467,1591552,1591704,1591713,1591715,1591723,1591874,1592487,1592512,1592658,1592665,1592677,1592742,1592744,1592787,1592809,1592955,1593036,1593048,1593061,1593133,1593210-1593211,1593231
 ,1593245,1593250,1593294,1593304,1593317,1593342,1593554,1594158-1594164,1594166-1594167,1594169,1594237,1594800,1594808,1594835,1594888,1595147,1595457,1595856,1596241,1596474,1596534,1596844,1597569,1597795,1597854,1597860,1598292,1598302,1598352,1598369,1598595,1598631,1598696,1598732,1598797-1598798,1599299,1599332,1599416,1599434,1599671,1600088,1600935,1601309,1601388,1601578,1601676,1601757,1601768,1601814,1601833,1601838,1601853,1601878,1601888,1601922,1602156,1602174,1602179,1602183,1602207,1602227,1602256,1602261,1602796-1602797,1602800,1602809,1602853,1602872,1602914,1603155,1603307,1603401,1603441,1603748,1604166,1605030,1605036,1605038,1605292,1605447,1605526,1605670,1605725,1605831,1605852,1606077,1606079,1606087,1606638,1606641,1606644,1606708,1606711,1607031-1607032,1607077,1607127,1607141,1607152,1607185,1607196,1607331,1607362,1607366,1607392,1607526,1607557,1607664,1607737,1608560,1608731,1608783,1609064,1609081,1609165,1609488,1610489,1610592,1610603,1610634,1610
 658,1610664,1611021,1611041,1611275,1611277,1611313,1611332,1611584,1612560,1612825,1612993,1613018,1613041,1614265,1614272,1614344-1614345,1614384-1614385,1614397,1614405-1614406,1614574,1614591,1614593,1614596,1614604,1614689,1614807,1614835,1614891,1615417-1615418,1616182,1616236,1616463,1616719,1617417,1617451,1617463,1617711,1618158,1618613,1618624,1618709,1619222,1619411,1619695,1619800,1619808,1619815,1619823-1619824,1620512,1620581,1620585,1620634,1620898,1620905,1621115,1621123-1621124,1621168,1621192,1621201,1621706,1621962,1622197,1622201,1622207,1622250,1622479,1623364,1623766,1623827,1623949,1623969,1623973,1624216,1624317,1624551,1624973,1624993-1624994,1625025,1625036,1625158,1625224,1625237,1625299,1625348,1625620,1625916,1625962-1625963,1626021,1626053,1626163,1626168,1626175,1626191,1626265,1626770,1627047,1627052,1627228,1627346,1627470,1627473,1627479,1627503,1627586,1627590,1627715,1627731,1628180,1628198,1628262,1628447,1628608,1629688,1629840,1629917,1630055-1
 630057,1630156,1630299,1630338,1630773,1631283-1631284,1631333-1631334,1631617-1631619,1631630,1631699,1631704,1631711,1631967-1631969,1631986,1631990,1631999,1632002-1632003,1632017,1632258,1632264,1632270,1632293,1632303,1632592,1632605,1633315,1633559-1633560,1633562,1633567,1633571,1633598,1633608,1633641,1633687,1633697,1633768,1633783,1634505,1634513,1634774,1634779,1634781,1634792,1634803,1634814,1634816,1634838,1634841,1634852,1634864,1634896,1634898,1635044-1635045,1635060,1635077,1635089,1635102,1635108,1635218,1635387,1635435,1635518,1635563,1635586,1636336,1636348,1636505,1636585,1636799,1637368,1637382,1637413,1637651,1637815,1638779-1638783,1639260,1639577,1639622,1639963,1639966,1639973,1640134,1640143,1640555-1640556,1640694-1640695,1640715,1640722-1640723,1640728,1640863-1640872,1641340,1641350,1641352,1641541,1641596-1641599,1641601,1641662,1641671,1641695,1641771,1641802,1641811,1641950,1642031,1642056,1642119,1642285,1642648,1642667,1642954,1642959,1643111,164317
 8,1643186,1643204,1643287,1643767,1643774,1643982,1644016,1644106,1644366,1644383,1644397-1644398,1644407,1644479,1644547,1644552,1644554,1644650,1644654,1644689,1644750,1645421,1645424,1645459,1645585,1645611,1645637,1645646,1645660-1645663,1645888,1645901,1645948,1645966,1645970-1645971,1646014,1646164,1646174,1649743,1649803,1650015,1650529,1650797
+/jackrabbit/oak/trunk:1584578,1584602,1584614,1584616,1584709,1584781,1584937,1585297,1585304-1585305,1585420,1585424,1585427,1585448,1585465,1585468,1585486,1585497,1585509,1585647,1585655-1585656,1585661,1585665-1585666,1585669-1585670,1585673,1585680,1585719,1585763,1585770,1585896,1585904,1585907,1585940,1585949,1585951,1585956,1585962-1585963,1586287,1586320,1586364,1586372,1586655,1586836,1587130,1587224,1587399,1587408,1587472,1587485,1587488,1587538,1587580,1587807,1588033,1588042,1588046,1588066,1588201,1589025,1589101,1589137,1589141,1589263,1589440,1589442,1589484,1589488,1589661,1589664,1589682,1589708,1589741,1589748,1589789,1589794,1589850,1589864,1590628,1590660,1590684,1590697,1590701,1590980,1590988,1591101,1591226,1591229,1591293,1591314,1591317,1591362,1591374,1591381,1591438,1591467,1591552,1591704,1591713,1591715,1591723,1591874,1592487,1592512,1592658,1592665,1592677,1592742,1592744,1592787,1592809,1592955,1593036,1593048,1593061,1593133,1593210-1593211,1593231
 ,1593245,1593250,1593294,1593304,1593317,1593342,1593554,1594158-1594164,1594166-1594167,1594169,1594237,1594800,1594808,1594835,1594888,1595147,1595457,1595856,1596241,1596474,1596534,1596844,1597569,1597795,1597854,1597860,1598292,1598302,1598352,1598369,1598595,1598631,1598696,1598732,1598797-1598798,1599299,1599332,1599416,1599434,1599671,1600088,1600935,1601309,1601388,1601578,1601676,1601757,1601768,1601814,1601833,1601838,1601853,1601878,1601888,1601922,1602156,1602174,1602179,1602183,1602207,1602227,1602256,1602261,1602796-1602797,1602800,1602809,1602853,1602872,1602914,1603155,1603307,1603401,1603441,1603748,1604166,1605030,1605036,1605038,1605292,1605447,1605526,1605670,1605725,1605831,1605852,1606077,1606079,1606087,1606638,1606641,1606644,1606708,1606711,1607031-1607032,1607077,1607127,1607141,1607152,1607185,1607196,1607331,1607362,1607366,1607392,1607526,1607557,1607664,1607737,1608560,1608731,1608783,1609064,1609081,1609165,1609488,1610489,1610592,1610603,1610634,1610
 658,1610664,1611021,1611041,1611275,1611277,1611313,1611332,1611584,1612560,1612825,1612993,1613018,1613041,1614265,1614272,1614344-1614345,1614384-1614385,1614397,1614405-1614406,1614574,1614591,1614593,1614596,1614604,1614689,1614807,1614835,1614891,1615417-1615418,1616182,1616236,1616463,1616719,1617417,1617451,1617463,1617711,1618158,1618613,1618624,1618709,1619222,1619411,1619695,1619800,1619808,1619815,1619823-1619824,1620512,1620581,1620585,1620634,1620898,1620905,1621115,1621123-1621124,1621168,1621192,1621201,1621706,1621962,1622197,1622201,1622207,1622250,1622479,1623364,1623766,1623827,1623949,1623969,1623973,1624216,1624317,1624551,1624973,1624993-1624994,1625025,1625036,1625158,1625224,1625237,1625299,1625348,1625620,1625916,1625962-1625963,1626021,1626053,1626163,1626168,1626175,1626191,1626265,1626770,1627047,1627052,1627228,1627346,1627470,1627473,1627479,1627503,1627586,1627590,1627715,1627731,1628180,1628198,1628262,1628447,1628608,1629688,1629840,1629917,1630055-1
 630057,1630156,1630299,1630338,1630773,1631283-1631284,1631333-1631334,1631617-1631619,1631630,1631699,1631704,1631711,1631967-1631969,1631986,1631990,1631999,1632002-1632003,1632017,1632258,1632264,1632270,1632293,1632303,1632592,1632605,1633315,1633559-1633560,1633562,1633567,1633571,1633598,1633608,1633641,1633687,1633697,1633768,1633783,1634505,1634513,1634774,1634779,1634781,1634792,1634803,1634814,1634816,1634838,1634841,1634852,1634864,1634896,1634898,1635044-1635045,1635060,1635077,1635089,1635102,1635108,1635218,1635387,1635435,1635518,1635563,1635586,1636336,1636348,1636505,1636585,1636799,1637368,1637382,1637413,1637651,1637815,1638779-1638783,1639260,1639577,1639622,1639963,1639966,1639973,1640134,1640143,1640555-1640556,1640694-1640695,1640715,1640722-1640723,1640728,1640863-1640872,1641340,1641350,1641352,1641541,1641596-1641599,1641601,1641662,1641671,1641695,1641771,1641802,1641811,1641950,1642031,1642056,1642119,1642285,1642648,1642667,1642954,1642959,1643111,164317
 8,1643186,1643204,1643287,1643767,1643774,1643982,1644016,1644106,1644366,1644383,1644397-1644398,1644407,1644479,1644547,1644552,1644554,1644650,1644654,1644689,1644750,1645421,1645424,1645459,1645585,1645611,1645637,1645646,1645660-1645663,1645888,1645901,1645948,1645966,1645970-1645971,1646014,1646164,1646174,1649743,1649803,1650015,1650239,1650529,1650797,1651323,1651382
 /jackrabbit/trunk:1345480

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentMK.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentMK.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentMK.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentMK.java Tue Jan 13 15:52:07 2015
@@ -31,24 +31,25 @@ import com.mongodb.DB;
 
 import org.apache.jackrabbit.mk.api.MicroKernel;
 import org.apache.jackrabbit.mk.api.MicroKernelException;
-import org.apache.jackrabbit.oak.spi.blob.BlobStore;
-import org.apache.jackrabbit.oak.spi.blob.GarbageCollectableBlobStore;
-import org.apache.jackrabbit.oak.spi.blob.MemoryBlobStore;
-import org.apache.jackrabbit.oak.commons.json.JsopReader;
-import org.apache.jackrabbit.oak.commons.json.JsopStream;
-import org.apache.jackrabbit.oak.commons.json.JsopTokenizer;
 import org.apache.jackrabbit.oak.api.CommitFailedException;
 import org.apache.jackrabbit.oak.cache.CacheLIRS;
 import org.apache.jackrabbit.oak.cache.CacheValue;
 import org.apache.jackrabbit.oak.cache.EmpiricalWeigher;
 import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.commons.json.JsopReader;
+import org.apache.jackrabbit.oak.commons.json.JsopStream;
+import org.apache.jackrabbit.oak.commons.json.JsopTokenizer;
 import org.apache.jackrabbit.oak.plugins.document.DocumentNodeState.Children;
-import org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore;
 import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
+import org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore;
 import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore;
+import org.apache.jackrabbit.oak.plugins.document.mongo.MongoVersionGCSupport;
 import org.apache.jackrabbit.oak.plugins.document.persistentCache.CacheType;
 import org.apache.jackrabbit.oak.plugins.document.persistentCache.PersistentCache;
 import org.apache.jackrabbit.oak.plugins.document.util.StringValue;
+import org.apache.jackrabbit.oak.spi.blob.BlobStore;
+import org.apache.jackrabbit.oak.spi.blob.GarbageCollectableBlobStore;
+import org.apache.jackrabbit.oak.spi.blob.MemoryBlobStore;
 import org.apache.jackrabbit.oak.stats.Clock;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -755,6 +756,15 @@ public class DocumentMK implements Micro
             return disableBranches;
         }
 
+        VersionGCSupport createVersionGCSupport() {
+            DocumentStore store = getDocumentStore();
+            if (store instanceof MongoDocumentStore) {
+                return new MongoVersionGCSupport((MongoDocumentStore) store);
+            } else {
+                return new VersionGCSupport(store);
+            }
+        }
+
         /**
          * Open the DocumentMK instance using the configured options.
          *

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java Tue Jan 13 15:52:07 2015
@@ -369,7 +369,8 @@ public final class DocumentNodeStore
         this.revisionComparator = new Revision.RevisionComparator(clusterId);
         this.branches = new UnmergedBranches(getRevisionComparator());
         this.asyncDelay = builder.getAsyncDelay();
-        this.versionGarbageCollector = new VersionGarbageCollector(this);
+        this.versionGarbageCollector = new VersionGarbageCollector(
+                this, builder.createVersionGCSupport());
         this.lastRevRecoveryAgent = new LastRevRecoveryAgent(this);
         this.disableBranches = builder.isDisableBranches();
         this.missing = new DocumentNodeState(this, "MISSING", new Revision(0, 0, 0)) {

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java Tue Jan 13 15:52:07 2015
@@ -57,6 +57,7 @@ import com.google.common.collect.Maps;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.collect.Iterables.filter;
 import static com.google.common.collect.Iterables.transform;
+import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES;
 import static org.apache.jackrabbit.oak.plugins.document.UpdateOp.Key;
 import static org.apache.jackrabbit.oak.plugins.document.UpdateOp.Operation;
 import static org.apache.jackrabbit.oak.plugins.document.util.Utils.isRevisionNewer;
@@ -153,7 +154,7 @@ public final class NodeDocument extends
      * <p>
      * Key: high revision
      * <p>
-     * Value: low revision
+     * Value: low revision / height (see {@link Range#getLowValue()}
      */
     private static final String PREVIOUS = "_prev";
 
@@ -208,6 +209,13 @@ public final class NodeDocument extends
 
     public static final String HAS_BINARY_FLAG = "_bin";
 
+    /**
+     * Contains {@link #PREVIOUS} entries that are considered stale (pointing
+     * to a previous document that had been deleted) and should be removed
+     * during the next split run.
+     */
+    private static final String STALE_PREV = "_stalePrev";
+
     //~----------------------------< Split Document Types >
 
     /**
@@ -321,7 +329,8 @@ public final class NodeDocument extends
     final DocumentStore store;
 
     /**
-     * Parsed and sorted set of previous revisions.
+     * Parsed and sorted set of previous revisions (without stale references
+     * to removed previous documents).
      */
     private NavigableMap<Revision, Range> previous;
 
@@ -981,27 +990,67 @@ public final class NodeDocument extends
 
     /**
      * Returns previous revision ranges for this document. The revision keys are
-     * sorted descending, newest first!
+     * sorted descending, newest first! The returned map does not include stale
+     * entries.
+     * This method is equivalent to calling {@link #getPreviousRanges(boolean)}
+     * with {@code includeStale} set to false.
      *
      * @return the previous ranges for this document.
      */
     @Nonnull
     NavigableMap<Revision, Range> getPreviousRanges() {
-        if (previous == null) {
-            Map<Revision, String> map = getLocalMap(PREVIOUS);
-            if (map.isEmpty()) {
-                previous = EMPTY_RANGE_MAP;
-            } else {
-                NavigableMap<Revision, Range> transformed = new TreeMap<Revision, Range>(
-                        StableRevisionComparator.REVERSE);
-                for (Map.Entry<Revision, String> entry : map.entrySet()) {
-                    Range r = Range.fromEntry(entry.getKey(), entry.getValue());
-                    transformed.put(r.high, r);
+        return getPreviousRanges(false);
+    }
+
+    /**
+     * Returns previous revision ranges for this document. The revision keys are
+     * sorted descending, newest first!
+     *
+     * @param includeStale whether stale revision ranges are included or not.
+     * @return the previous ranges for this document.
+     */
+    @Nonnull
+    NavigableMap<Revision, Range> getPreviousRanges(boolean includeStale) {
+        if (includeStale) {
+            return createPreviousRanges(true);
+        } else {
+            if (previous == null) {
+                previous = createPreviousRanges(false);
+            }
+            return previous;
+        }
+    }
+
+    /**
+     * Creates a map with previous revision ranges for this document. The
+     * revision keys are sorted descending, newest first!
+     *
+     * @param includeStale whether stale revision ranges are included or not.
+     * @return the previous ranges for this document.
+     */
+    @Nonnull
+    private NavigableMap<Revision, Range> createPreviousRanges(boolean includeStale) {
+        NavigableMap<Revision, Range> ranges;
+        Map<Revision, String> map = getLocalMap(PREVIOUS);
+        if (map.isEmpty()) {
+            ranges = EMPTY_RANGE_MAP;
+        } else {
+            Map<Revision, String> stale = Collections.emptyMap();
+            if (!includeStale) {
+                stale = getLocalMap(STALE_PREV);
+            }
+            NavigableMap<Revision, Range> transformed = new TreeMap<Revision, Range>(
+                    StableRevisionComparator.REVERSE);
+            for (Map.Entry<Revision, String> entry : map.entrySet()) {
+                Range r = Range.fromEntry(entry.getKey(), entry.getValue());
+                if (String.valueOf(r.height).equals(stale.get(r.high))) {
+                    continue;
                 }
-                previous = Maps.unmodifiableNavigableMap(transformed);
+                transformed.put(r.high, r);
             }
+            ranges = Maps.unmodifiableNavigableMap(transformed);
         }
-        return previous;
+        return ranges;
     }
 
     /**
@@ -1105,6 +1154,40 @@ public final class NodeDocument extends
     }
 
     /**
+     * Returns the document that contains a reference to the previous document
+     * identified by {@code revision} and {@code height}. This is either the
+     * current document or an intermediate split document. This method returns
+     * {@code null} if there is no such reference.
+     *
+     * @param revision the high revision of a range entry in {@link #PREVIOUS}.
+     * @param height the height of the entry in {@link #PREVIOUS}.
+     * @return the document with the entry or {@code null} if not found.
+     */
+    @Nullable
+    NodeDocument findPrevReferencingDoc(Revision revision, int height) {
+        for (Range range : getPreviousRanges().values()) {
+            if (range.getHeight() == height && range.high.equals(revision)) {
+                return this;
+            } else if (range.includes(revision)) {
+                String prevId = Utils.getPreviousIdFor(
+                        getMainPath(), range.high, range.height);
+                NodeDocument prev = store.find(NODES, prevId);
+                if (prev == null) {
+                    LOG.warn("Split document {} does not exist anymore. Main document is {}",
+                            prevId, Utils.getIdFromPath(getMainPath()));
+                    continue;
+                }
+                // recurse into the split hierarchy
+                NodeDocument doc = prev.findPrevReferencingDoc(revision, height);
+                if (doc != null) {
+                    return doc;
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
      * Returns the local value map for the given key.
      *
      * @param key the key.
@@ -1138,6 +1221,11 @@ public final class NodeDocument extends
         return getLocalMap(DELETED);
     }
 
+    @Nonnull
+    SortedMap<Revision, String> getStalePrev() {
+        return getLocalMap(STALE_PREV);
+    }
+
     //-------------------------< UpdateOp modifiers >---------------------------
 
     public static void setChildrenFlag(@Nonnull UpdateOp op,
@@ -1240,7 +1328,24 @@ public final class NodeDocument extends
 
     public static void removePrevious(@Nonnull UpdateOp op,
                                       @Nonnull Range range) {
-        checkNotNull(op).removeMapEntry(PREVIOUS, checkNotNull(range).high);
+        removePrevious(op, checkNotNull(range).high);
+    }
+
+    public static void removePrevious(@Nonnull UpdateOp op,
+                                      @Nonnull Revision revision) {
+        checkNotNull(op).removeMapEntry(PREVIOUS, checkNotNull(revision));
+    }
+
+    public static void setStalePrevious(@Nonnull UpdateOp op,
+                                        @Nonnull Revision revision,
+                                        int height) {
+        checkNotNull(op).setMapEntry(STALE_PREV,
+                checkNotNull(revision), String.valueOf(height));
+    }
+
+    public static void removeStalePrevious(@Nonnull UpdateOp op,
+                                           @Nonnull Revision revision) {
+        checkNotNull(op).removeMapEntry(STALE_PREV, checkNotNull(revision));
     }
 
     public static void setHasBinary(@Nonnull UpdateOp op) {

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitOperations.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitOperations.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitOperations.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/SplitOperations.java Tue Jan 13 15:52:07 2015
@@ -33,6 +33,8 @@ import javax.annotation.Nonnull;
 
 import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
 import org.apache.jackrabbit.oak.plugins.document.util.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
@@ -52,6 +54,7 @@ import static org.apache.jackrabbit.oak.
 import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.removePrevious;
 import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.setHasBinary;
 import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.setPrevious;
+import static org.apache.jackrabbit.oak.plugins.document.util.Utils.getPreviousIdFor;
 import static org.apache.jackrabbit.oak.plugins.document.util.Utils.isRevisionNewer;
 
 /**
@@ -59,6 +62,7 @@ import static org.apache.jackrabbit.oak.
  */
 class SplitOperations {
 
+    private static final Logger LOG = LoggerFactory.getLogger(SplitOperations.class);
     private static final DocumentStore STORE = new MemoryDocumentStore();
 
     private final NodeDocument doc;
@@ -127,8 +131,11 @@ class SplitOperations {
         // create intermediate docs if needed
         createIntermediateDocs();
 
+        // remove stale references to previous docs
+        disconnectStalePrevDocs();
+
         // main document must be updated last
-        if (main != null && !splitOps.isEmpty()) {
+        if (main != null) {
             splitOps.add(main);
         }
 
@@ -141,7 +148,8 @@ class SplitOperations {
         // unless document is really big
         return doc.getLocalRevisions().size() + doc.getLocalCommitRoot().size() > NUM_REVS_THRESHOLD
                 || doc.getMemory() >= DOC_SIZE_THRESHOLD
-                || previous.size() >= PREV_SPLIT_FACTOR;
+                || previous.size() >= PREV_SPLIT_FACTOR
+                || !doc.getStalePrev().isEmpty();
     }
 
     /**
@@ -368,6 +376,41 @@ class SplitOperations {
         return committedLocally;
     }
 
+    private void disconnectStalePrevDocs() {
+        NavigableMap<Revision, Range> ranges = doc.getPreviousRanges(true);
+        for (Map.Entry<Revision, String> entry : doc.getStalePrev().entrySet()) {
+            Revision r = entry.getKey();
+            if (r.getClusterId() != context.getClusterId()) {
+                // only process revisions of this cluster node
+                continue;
+            }
+            if (main == null) {
+                main = new UpdateOp(id, false);
+            }
+            NodeDocument.removeStalePrevious(main, r);
+
+            if (ranges.containsKey(r)
+                    && entry.getValue().equals(String.valueOf(ranges.get(r).height))) {
+                NodeDocument.removePrevious(main, r);
+            } else {
+                // reference was moved to an intermediate doc
+                // while the last GC was running
+                // -> need to locate intermediate doc and disconnect from there
+                int height = Integer.parseInt(entry.getValue());
+                NodeDocument intermediate = doc.findPrevReferencingDoc(r, height);
+                if (intermediate == null) {
+                    LOG.warn("Split document {} not referenced anymore. Main document is {}",
+                            getPreviousIdFor(doc.getPath(), r, height), id);
+                } else {
+                    UpdateOp op = new UpdateOp(intermediate.getId(), false);
+                    NodeDocument.removePrevious(op, r);
+                    splitOps.add(op);
+                }
+            }
+
+        }
+    }
+
     private void trackHigh(Revision r) {
         if (high == null || isRevisionNewer(context, r, high)) {
             high = r;

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGCSupport.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGCSupport.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGCSupport.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGCSupport.java Tue Jan 13 15:52:07 2015
@@ -19,16 +19,18 @@
 
 package org.apache.jackrabbit.oak.plugins.document;
 
-import java.util.List;
 import java.util.Set;
 
 import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
 
+import org.apache.jackrabbit.oak.plugins.document.VersionGarbageCollector.VersionGCStats;
+
+import static com.google.common.collect.Iterables.filter;
 import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.SplitDocType;
+import static org.apache.jackrabbit.oak.plugins.document.util.Utils.getAllDocuments;
 
 public class VersionGCSupport {
+
     private final DocumentStore store;
 
     public VersionGCSupport(DocumentStore store) {
@@ -36,7 +38,7 @@ public class VersionGCSupport {
     }
 
     public Iterable<NodeDocument> getPossiblyDeletedDocs(final long lastModifiedTime) {
-        return Iterables.filter(getAllDocuments(), new Predicate<NodeDocument>() {
+        return filter(getAllDocuments(store), new Predicate<NodeDocument>() {
             @Override
             public boolean apply(NodeDocument input) {
                 return input.wasDeletedOnce() && !input.hasBeenModifiedSince(lastModifiedTime);
@@ -44,21 +46,29 @@ public class VersionGCSupport {
         });
     }
 
-    public int deleteSplitDocuments(Set<SplitDocType> gcTypes, long oldestRevTimeStamp) {
-        List<String> docsToDelete = Lists.newArrayList();
-        for(NodeDocument doc : getAllDocuments()){
-            SplitDocType splitType = doc.getSplitDocType();
-            if(gcTypes.contains(splitType) && doc.hasAllRevisionLessThan(oldestRevTimeStamp)){
-                docsToDelete.add(doc.getId());
-            }
-        }
-        store.remove(Collection.NODES, docsToDelete);
-        return docsToDelete.size();
+    public void deleteSplitDocuments(Set<SplitDocType> gcTypes,
+                                     long oldestRevTimeStamp,
+                                     VersionGCStats stats) {
+        stats.splitDocGCCount += createCleanUp(gcTypes, oldestRevTimeStamp, stats)
+                .disconnect()
+                .deleteSplitDocuments();
+    }
+
+    protected SplitDocumentCleanUp createCleanUp(Set<SplitDocType> gcTypes,
+                                                 long oldestRevTimeStamp,
+                                                 VersionGCStats stats) {
+        return new SplitDocumentCleanUp(store, stats,
+                identifyGarbage(gcTypes, oldestRevTimeStamp));
     }
 
-    private List<NodeDocument> getAllDocuments() {
-        //Fetch all documents.
-        return store.query(Collection.NODES,NodeDocument.MIN_ID_VALUE,
-                NodeDocument.MAX_ID_VALUE, Integer.MAX_VALUE);
+    protected Iterable<NodeDocument> identifyGarbage(final Set<SplitDocType> gcTypes,
+                                                     final long oldestRevTimeStamp) {
+        return filter(getAllDocuments(store), new Predicate<NodeDocument>() {
+            @Override
+            public boolean apply(NodeDocument doc) {
+                return gcTypes.contains(doc.getSplitDocType())
+                        && doc.hasAllRevisionLessThan(oldestRevTimeStamp);
+            }
+        });
     }
 }

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollector.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollector.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollector.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollector.java Tue Jan 13 15:52:07 2015
@@ -29,8 +29,7 @@ import com.google.common.base.Joiner;
 import com.google.common.base.StandardSystemProperty;
 import com.google.common.base.Stopwatch;
 import com.google.common.collect.ImmutableList;
-import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore;
-import org.apache.jackrabbit.oak.plugins.document.mongo.MongoVersionGCSupport;
+
 import org.apache.jackrabbit.oak.plugins.document.util.Utils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -50,15 +49,10 @@ public class VersionGarbageCollector {
     private static final Set<NodeDocument.SplitDocType> GC_TYPES = EnumSet.of(
             DEFAULT_LEAF, COMMIT_ROOT_ONLY);
 
-    VersionGarbageCollector(DocumentNodeStore nodeStore) {
+    VersionGarbageCollector(DocumentNodeStore nodeStore,
+                            VersionGCSupport gcSupport) {
         this.nodeStore = nodeStore;
-
-        if(nodeStore.getDocumentStore() instanceof MongoDocumentStore){
-            this.versionStore =
-                    new MongoVersionGCSupport((MongoDocumentStore) nodeStore.getDocumentStore());
-        }else {
-            this.versionStore = new VersionGCSupport(nodeStore.getDocumentStore());
-        }
+        this.versionStore = gcSupport;
     }
 
     public VersionGCStats gc(long maxRevisionAge, TimeUnit unit) {
@@ -91,8 +85,7 @@ public class VersionGarbageCollector {
     }
 
     private void collectSplitDocuments(VersionGCStats stats, long oldestRevTimeStamp) {
-        int count = versionStore.deleteSplitDocuments(GC_TYPES, oldestRevTimeStamp);
-        stats.splitDocGCCount += count;
+        versionStore.deleteSplitDocuments(GC_TYPES, oldestRevTimeStamp, stats);
     }
 
     private void collectDeletedDocuments(VersionGCStats stats, Revision headRevision, long oldestRevTimeStamp) {
@@ -130,6 +123,7 @@ public class VersionGarbageCollector {
         boolean ignoredGCDueToCheckPoint;
         int deletedDocGCCount;
         int splitDocGCCount;
+        int intermediateSplitDocGCCount;
 
 
         @Override
@@ -138,6 +132,7 @@ public class VersionGarbageCollector {
                     "ignoredGCDueToCheckPoint=" + ignoredGCDueToCheckPoint +
                     ", deletedDocGCCount=" + deletedDocGCCount +
                     ", splitDocGCCount=" + splitDocGCCount +
+                    ", intermediateSplitDocGCCount=" + intermediateSplitDocGCCount +
                     '}';
         }
     }

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java Tue Jan 13 15:52:07 2015
@@ -805,6 +805,8 @@ public class MongoDocumentStore implemen
                     copy.put(key, o);
                 } else if (o instanceof Long) {
                     copy.put(key, o);
+                } else if (o instanceof Integer) {
+                    copy.put(key, o);
                 } else if (o instanceof Boolean) {
                     copy.put(key, o);
                 } else if (o instanceof BasicDBObject) {

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoVersionGCSupport.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoVersionGCSupport.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoVersionGCSupport.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoVersionGCSupport.java Tue Jan 13 15:52:07 2015
@@ -22,8 +22,6 @@ package org.apache.jackrabbit.oak.plugin
 import java.util.List;
 import java.util.Set;
 
-import javax.annotation.Nullable;
-
 import com.google.common.base.Function;
 import com.google.common.base.Joiner;
 import com.google.common.base.StandardSystemProperty;
@@ -36,16 +34,18 @@ import com.mongodb.DBObject;
 import com.mongodb.QueryBuilder;
 import com.mongodb.ReadPreference;
 import com.mongodb.WriteResult;
-import org.apache.jackrabbit.oak.plugins.document.Collection;
 import org.apache.jackrabbit.oak.plugins.document.Document;
 import org.apache.jackrabbit.oak.plugins.document.NodeDocument;
+import org.apache.jackrabbit.oak.plugins.document.SplitDocumentCleanUp;
 import org.apache.jackrabbit.oak.plugins.document.VersionGCSupport;
+import org.apache.jackrabbit.oak.plugins.document.VersionGarbageCollector.VersionGCStats;
 import org.apache.jackrabbit.oak.plugins.document.util.CloseableIterable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static com.google.common.collect.Iterables.transform;
 import static com.mongodb.QueryBuilder.start;
+import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES;
 import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.SplitDocType;
 
 /**
@@ -56,7 +56,7 @@ import static org.apache.jackrabbit.oak.
  * documents. In such case read from secondaries are preferred</p>
  */
 public class MongoVersionGCSupport extends VersionGCSupport {
-    private final Logger log = LoggerFactory.getLogger(getClass());
+    private static final Logger LOG = LoggerFactory.getLogger(MongoVersionGCSupport.class);
     private final MongoDocumentStore store;
 
     public MongoVersionGCSupport(MongoDocumentStore store) {
@@ -75,39 +75,45 @@ public class MongoVersionGCSupport exten
         return CloseableIterable.wrap(transform(cursor, new Function<DBObject, NodeDocument>() {
             @Override
             public NodeDocument apply(DBObject input) {
-                return store.convertFromDBObject(Collection.NODES, input);
+                return store.convertFromDBObject(NODES, input);
             }
         }), cursor);
     }
 
     @Override
-    public int deleteSplitDocuments(Set<SplitDocType> gcTypes, long oldestRevTimeStamp) {
+    protected SplitDocumentCleanUp createCleanUp(Set<SplitDocType> gcTypes,
+                                                 long oldestRevTimeStamp,
+                                                 VersionGCStats stats) {
+        return new MongoSplitDocCleanUp(gcTypes, oldestRevTimeStamp, stats);
+    }
+
+    @Override
+    protected Iterable<NodeDocument> identifyGarbage(final Set<SplitDocType> gcTypes,
+                                                     final long oldestRevTimeStamp) {
+        return transform(getNodeCollection().find(createQuery(gcTypes, oldestRevTimeStamp)),
+                new Function<DBObject, NodeDocument>() {
+            @Override
+            public NodeDocument apply(DBObject input) {
+                return store.convertFromDBObject(NODES, input);
+            }
+        });
+    }
+
+    private DBObject createQuery(Set<SplitDocType> gcTypes,
+                                 long oldestRevTimeStamp) {
         //OR condition has to be first as we have a index for that
         //((type == DEFAULT_NO_CHILD || type == PROP_COMMIT_ONLY ..) && _sdMaxRevTime < oldestRevTimeStamp(in secs)
         QueryBuilder orClause = start();
         for(SplitDocType type : gcTypes){
             orClause.or(start(NodeDocument.SD_TYPE).is(type.typeCode()).get());
         }
-        DBObject query = start()
+        return start()
                 .and(
-                    orClause.get(),
-                    start(NodeDocument.SD_MAX_REV_TIME_IN_SECS)
-                        .lessThan(NodeDocument.getModifiedInSecs(oldestRevTimeStamp))
-                        .get()
+                        orClause.get(),
+                        start(NodeDocument.SD_MAX_REV_TIME_IN_SECS)
+                                .lessThan(NodeDocument.getModifiedInSecs(oldestRevTimeStamp))
+                                .get()
                 ).get();
-
-        if(log.isDebugEnabled()){
-            //if debug level logging is on then determine the id of documents to be deleted
-            //and log them
-            logSplitDocIdsTobeDeleted(query);
-        }
-
-        WriteResult writeResult = getNodeCollection().remove(query);
-        if (writeResult.getError() != null) {
-            //TODO This might be temporary error or we fail fast and let next cycle try again
-            log.warn("Error occurred while deleting old split documents from Mongo {}", writeResult.getError());
-        }
-        return writeResult.getN();
     }
 
     private void logSplitDocIdsTobeDeleted(DBObject query) {
@@ -115,11 +121,11 @@ public class MongoVersionGCSupport exten
         final BasicDBObject keys = new BasicDBObject(Document.ID, 1);
         List<String> ids;
         DBCursor cursor = getNodeCollection().find(query, keys)
-                .setReadPreference(store.getConfiguredReadPreference(Collection.NODES));
+                .setReadPreference(store.getConfiguredReadPreference(NODES));
         try {
              ids = ImmutableList.copyOf(Iterables.transform(cursor, new Function<DBObject, String>() {
                  @Override
-                 public String apply(@Nullable DBObject input) {
+                 public String apply(DBObject input) {
                      return (String) input.get(Document.ID);
                  }
              }));
@@ -128,10 +134,43 @@ public class MongoVersionGCSupport exten
         }
         StringBuilder sb = new StringBuilder("Split documents with following ids were deleted as part of GC \n");
         Joiner.on(StandardSystemProperty.LINE_SEPARATOR.value()).appendTo(sb, ids);
-        log.debug(sb.toString());
+        LOG.debug(sb.toString());
     }
 
     private DBCollection getNodeCollection(){
-        return store.getDBCollection(Collection.NODES);
+        return store.getDBCollection(NODES);
+    }
+
+    private class MongoSplitDocCleanUp extends SplitDocumentCleanUp {
+
+        protected final Set<SplitDocType> gcTypes;
+        protected final long oldestRevTimeStamp;
+
+        protected MongoSplitDocCleanUp(Set<SplitDocType> gcTypes,
+                                       long oldestRevTimeStamp,
+                                       VersionGCStats stats) {
+            super(MongoVersionGCSupport.this.store, stats,
+                    identifyGarbage(gcTypes, oldestRevTimeStamp));
+            this.gcTypes = gcTypes;
+            this.oldestRevTimeStamp = oldestRevTimeStamp;
+        }
+
+        @Override
+        protected int deleteSplitDocuments() {
+            DBObject query = createQuery(gcTypes, oldestRevTimeStamp);
+
+            if(LOG.isDebugEnabled()){
+                //if debug level logging is on then determine the id of documents to be deleted
+                //and log them
+                logSplitDocIdsTobeDeleted(query);
+            }
+
+            WriteResult writeResult = getNodeCollection().remove(query);
+            if (writeResult.getError() != null) {
+                //TODO This might be temporary error or we fail fast and let next cycle try again
+                LOG.warn("Error occurred while deleting old split documents from Mongo {}", writeResult.getError());
+            }
+            return writeResult.getN();
+        }
     }
 }

Modified: jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java Tue Jan 13 15:52:07 2015
@@ -23,6 +23,7 @@ import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.sql.Timestamp;
 import java.util.Comparator;
+import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.SortedMap;
@@ -32,10 +33,14 @@ import javax.annotation.CheckForNull;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 
+import com.google.common.collect.AbstractIterator;
 import com.mongodb.BasicDBObject;
 
 import org.apache.commons.codec.binary.Hex;
 import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.plugins.document.Collection;
+import org.apache.jackrabbit.oak.plugins.document.DocumentStore;
+import org.apache.jackrabbit.oak.plugins.document.NodeDocument;
 import org.apache.jackrabbit.oak.plugins.document.Revision;
 import org.apache.jackrabbit.oak.plugins.document.RevisionContext;
 import org.bson.types.ObjectId;
@@ -462,4 +467,51 @@ public class Utils {
         return context.getRevisionComparator().compare(x, previous) > 0;
     }
 
+    /**
+     * Returns an iterable over all {@code NodeDocument}s in the given store.
+     * The returned iterable does not guarantee a consistent view on the store.
+     * The iterator may return documents that have been added to the store after
+     * this method had been called.
+     *
+     * @param store a document store.
+     * @return an iterable over all documents in the store.
+     */
+    public static Iterable<NodeDocument> getAllDocuments(final DocumentStore store) {
+        return new Iterable<NodeDocument>() {
+            @Override
+            public Iterator<NodeDocument> iterator() {
+                return new AbstractIterator<NodeDocument>() {
+
+                    private static final int BATCH_SIZE = 100;
+                    private String startId = NodeDocument.MIN_ID_VALUE;
+
+                    private Iterator<NodeDocument> batch = nextBatch();
+
+                    @Override
+                    protected NodeDocument computeNext() {
+                        // read next batch if necessary
+                        if (!batch.hasNext()) {
+                            batch = nextBatch();
+                        }
+
+                        NodeDocument doc;
+                        if (batch.hasNext()) {
+                            doc = batch.next();
+                            // remember current id
+                            startId = doc.getId();
+                        } else {
+                            doc = endOfData();
+                        }
+                        return doc;
+                    }
+
+                    private Iterator<NodeDocument> nextBatch() {
+                        return store.query(Collection.NODES, startId,
+                                NodeDocument.MAX_ID_VALUE, BATCH_SIZE).iterator();
+                    }
+                };
+            }
+        };
+    }
+
 }

Modified: jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollectorTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollectorTest.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollectorTest.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/VersionGarbageCollectorTest.java Tue Jan 13 15:52:07 2015
@@ -16,7 +16,6 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-
 package org.apache.jackrabbit.oak.plugins.document;
 
 import java.io.IOException;
@@ -26,6 +25,8 @@ import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
+import static com.google.common.collect.Iterables.size;
+import static java.util.concurrent.TimeUnit.HOURS;
 import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES;
 import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.NUM_REVS_THRESHOLD;
 import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.PREV_SPLIT_FACTOR;
@@ -38,9 +39,11 @@ import static org.junit.Assert.assertNul
 import static org.junit.Assert.assertTrue;
 
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterators;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 
+import org.apache.jackrabbit.oak.api.CommitFailedException;
 import org.apache.jackrabbit.oak.plugins.document.util.Utils;
 import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
 import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
@@ -97,6 +100,7 @@ public class VersionGarbageCollectorTest
     @After
     public void tearDown() throws Exception {
         store.dispose();
+        Revision.resetClockToDefault();
     }
 
     @Test
@@ -128,7 +132,7 @@ public class VersionGarbageCollectorTest
         long delta = TimeUnit.MINUTES.toMillis(10);
         //1. Go past GC age and check no GC done as nothing deleted
         clock.waitUntil(Revision.getCurrentTimestamp() + maxAge);
-        VersionGCStats stats = gc.gc(maxAge, TimeUnit.HOURS);
+        VersionGCStats stats = gc.gc(maxAge, HOURS);
         assertEquals(0, stats.deletedDocGCCount);
 
         //Remove x/y
@@ -142,13 +146,13 @@ public class VersionGarbageCollectorTest
         //maxAge
         //Clock cannot move back (it moved forward in #1) so double the maxAge
         clock.waitUntil(clock.getTime() + delta);
-        stats = gc.gc(maxAge*2, TimeUnit.HOURS);
+        stats = gc.gc(maxAge*2, HOURS);
         assertEquals(0, stats.deletedDocGCCount);
 
         //3. Check that deleted doc does get collected post maxAge
-        clock.waitUntil(clock.getTime() + TimeUnit.HOURS.toMillis(maxAge*2) + delta);
+        clock.waitUntil(clock.getTime() + HOURS.toMillis(maxAge*2) + delta);
 
-        stats = gc.gc(maxAge*2, TimeUnit.HOURS);
+        stats = gc.gc(maxAge*2, HOURS);
         assertEquals(1, stats.deletedDocGCCount);
 
         //4. Check that a revived doc (deleted and created again) does not get gc
@@ -160,8 +164,8 @@ public class VersionGarbageCollectorTest
         b4.child("z");
         store.merge(b4, EmptyHook.INSTANCE, CommitInfo.EMPTY);
 
-        clock.waitUntil(clock.getTime() + TimeUnit.HOURS.toMillis(maxAge*2) + delta);
-        stats = gc.gc(maxAge*2, TimeUnit.HOURS);
+        clock.waitUntil(clock.getTime() + HOURS.toMillis(maxAge*2) + delta);
+        stats = gc.gc(maxAge*2, HOURS);
         assertEquals(0, stats.deletedDocGCCount);
 
     }
@@ -178,7 +182,7 @@ public class VersionGarbageCollectorTest
 
         //Commit on a node which has a child and where the commit root
         // is parent
-        for (int i = 0; i < NodeDocument.NUM_REVS_THRESHOLD; i++) {
+        for (int i = 0; i < NUM_REVS_THRESHOLD; i++) {
             b1 = store.getRoot().builder();
             //This updates a middle node i.e. one which has child bar
             //Should result in SplitDoc of type PROP_COMMIT_ONLY
@@ -201,8 +205,8 @@ public class VersionGarbageCollectorTest
         assertEquals(SplitDocType.COMMIT_ROOT_ONLY, previousDocTestFoo.get(0).getSplitDocType());
         assertEquals(SplitDocType.DEFAULT_LEAF, previousDocTestFoo2.get(0).getSplitDocType());
 
-        clock.waitUntil(clock.getTime() + TimeUnit.HOURS.toMillis(maxAge) + delta);
-        VersionGCStats stats = gc.gc(maxAge, TimeUnit.HOURS);
+        clock.waitUntil(clock.getTime() + HOURS.toMillis(maxAge) + delta);
+        VersionGCStats stats = gc.gc(maxAge, HOURS);
         assertEquals(2, stats.splitDocGCCount);
 
         //Previous doc should be removed
@@ -258,8 +262,8 @@ public class VersionGarbageCollectorTest
         assertTrue("Test data does not have intermediate previous docs",
                 hasIntermediateDoc);
 
-        clock.waitUntil(clock.getTime() + TimeUnit.HOURS.toMillis(maxAge) + delta);
-        VersionGCStats stats = gc.gc(maxAge, TimeUnit.HOURS);
+        clock.waitUntil(clock.getTime() + HOURS.toMillis(maxAge) + delta);
+        VersionGCStats stats = gc.gc(maxAge, HOURS);
         assertEquals(10, stats.splitDocGCCount);
 
         DocumentNodeState test = getDoc("/test").getNodeAtRevision(
@@ -293,9 +297,9 @@ public class VersionGarbageCollectorTest
 
         store.merge(b1, EmptyHook.INSTANCE, CommitInfo.EMPTY);
 
-        clock.waitUntil(clock.getTime() + TimeUnit.HOURS.toMillis(maxAge) + delta);
+        clock.waitUntil(clock.getTime() + HOURS.toMillis(maxAge) + delta);
 
-        VersionGCStats stats = gc.gc(maxAge, TimeUnit.HOURS);
+        VersionGCStats stats = gc.gc(maxAge, HOURS);
         assertEquals(1, stats.deletedDocGCCount);
 
         Set<String> children = Sets.newHashSet();
@@ -320,9 +324,9 @@ public class VersionGarbageCollectorTest
 
         store.runBackgroundOperations();
 
-        clock.waitUntil(clock.getTime() + TimeUnit.HOURS.toMillis(maxAge) + delta);
+        clock.waitUntil(clock.getTime() + HOURS.toMillis(maxAge) + delta);
 
-        VersionGCStats stats = gc.gc(maxAge, TimeUnit.HOURS);
+        VersionGCStats stats = gc.gc(maxAge, HOURS);
         assertEquals(2, stats.splitDocGCCount);
 
         NodeDocument doc = getDoc("/foo");
@@ -332,6 +336,54 @@ public class VersionGarbageCollectorTest
         assertNotNull(state);
     }
 
+    // OAK-1791
+    @Test
+    public void gcDefaultLeafSplitDocs() throws Exception {
+        Revision.setClock(clock);
+
+        NodeBuilder builder = store.getRoot().builder();
+        builder.child("test").setProperty("prop", -1);
+        merge(store, builder);
+
+        String id = Utils.getIdFromPath("/test");
+        long start = Revision.getCurrentTimestamp();
+        // simulate continuous writes once a second for one day
+        // collect garbage older than one hour
+        int hours = 24;
+        if (fixture instanceof DocumentStoreFixture.MongoFixture) {
+            // only run for 6 hours on MongoDB to
+            // keep time to run on a reasonable level
+            hours = 6;
+        }
+        for (int i = 0; i < 3600 * hours; i++) {
+            clock.waitUntil(start + i * 1000);
+            builder = store.getRoot().builder();
+            builder.child("test").setProperty("prop", i);
+            merge(store, builder);
+            if (i % 10 == 0) {
+                store.runBackgroundOperations();
+            }
+            // trigger GC twice an hour
+            if (i % 1800 == 0) {
+                gc.gc(1, HOURS);
+                NodeDocument doc = store.getDocumentStore().find(NODES, id);
+                assertNotNull(doc);
+                int numPrevDocs = Iterators.size(doc.getAllPreviousDocs());
+                assertTrue("too many previous docs: " + numPrevDocs,
+                        numPrevDocs < 70);
+            }
+        }
+        NodeDocument doc = store.getDocumentStore().find(NODES, id);
+        assertNotNull(doc);
+        int numRevs = size(doc.getValueMap("prop").entrySet());
+        assertTrue("too many revisions: " + numRevs, numRevs < 6000);
+    }
+
+    private void merge(DocumentNodeStore store, NodeBuilder builder)
+            throws CommitFailedException {
+        store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
+    }
+
     private NodeDocument getDoc(String path){
         return store.getDocumentStore().find(NODES, Utils.getIdFromPath(path), 0);
     }

Modified: jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/util/UtilsTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/util/UtilsTest.java?rev=1651391&r1=1651390&r2=1651391&view=diff
==============================================================================
--- jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/util/UtilsTest.java (original)
+++ jackrabbit/oak/branches/1.0/oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/util/UtilsTest.java Tue Jan 13 15:52:07 2015
@@ -17,8 +17,16 @@
 package org.apache.jackrabbit.oak.plugins.document.util;
 
 import com.google.common.base.Strings;
+import com.google.common.collect.Iterables;
+
+import org.apache.jackrabbit.oak.api.CommitFailedException;
 import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.plugins.document.DocumentMK;
+import org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore;
 import org.apache.jackrabbit.oak.plugins.document.Revision;
+import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
+import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
+import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
 import org.junit.Ignore;
 import org.junit.Test;
 
@@ -91,4 +99,21 @@ public class UtilsTest {
         time = System.currentTimeMillis() - time;
         System.out.println(time);
     }
+
+    @Test
+    public void getAllDocuments() throws CommitFailedException {
+        DocumentNodeStore store = new DocumentMK.Builder().getNodeStore();
+        try {
+            NodeBuilder builder = store.getRoot().builder();
+            for (int i = 0; i < 1000; i++) {
+                builder.child("test-" + i);
+            }
+            store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
+
+            assertEquals(1001 /* root + 1000 children */, Iterables.size(
+                    Utils.getAllDocuments(store.getDocumentStore())));
+        } finally {
+            store.dispose();
+        }
+    }
 }