<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[12182] CalendarServer/branches/users/gaya/cleanrevisions</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/12182">12182</a></dd>
<dt>Author</dt> <dd>gaya@apple.com</dd>
<dt>Date</dt> <dd>2013-12-20 20:32:24 -0800 (Fri, 20 Dec 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>checkpoint</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionscalendarservertapcaldavpy">CalendarServer/branches/users/gaya/cleanrevisions/calendarserver/tap/caldav.py</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstwistedcaldavstdconfigpy">CalendarServer/branches/users/gaya/cleanrevisions/twistedcaldav/stdconfig.py</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcarddavdatastoresqlpy">CalendarServer/branches/users/gaya/cleanrevisions/txdav/carddav/datastore/sql.py</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresqlpy">CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql.py</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemacurrentoracledialectsql">CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current-oracle-dialect.sql</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemacurrentsql">CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current.sql</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemaupgradesoracledialectupgrade_from_30_to_31sql">CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_30_to_31.sql</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemaupgradespostgresdialectupgrade_from_30_to_31sql">CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_30_to_31.sql</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li>CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/</li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastorework__init__py">CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/__init__.py</a></li>
<li><a href="#CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoreworkrevision_cleanuppy">CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/revision_cleanup.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServerbranchesusersgayacleanrevisionscalendarservertapcaldavpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/calendarserver/tap/caldav.py (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/calendarserver/tap/caldav.py        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/calendarserver/tap/caldav.py        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -37,54 +37,55 @@
</span><span class="cx"> 
</span><span class="cx"> from zope.interface import implements
</span><span class="cx"> 
</span><ins>+from twisted.application.internet import TCPServer, UNIXServer
+from twisted.application.service import MultiService, IServiceMaker
+from twisted.application.service import Service
+from twisted.internet.defer import gatherResults, Deferred, inlineCallbacks, succeed
+from twisted.internet.endpoints import UNIXClientEndpoint, TCP4ClientEndpoint
+from twisted.internet.process import ProcessExitedAlready
+from twisted.internet.protocol import ProcessProtocol
+from twisted.internet.protocol import Protocol, Factory
+from twisted.plugin import IPlugin
+from twisted.protocols.amp import AMP
</ins><span class="cx"> from twisted.python.log import FileLogObserver, ILogObserver
</span><span class="cx"> from twisted.python.logfile import LogFile
</span><span class="cx"> from twisted.python.usage import Options, UsageError
</span><span class="cx"> from twisted.python.util import uidFromString, gidFromString
</span><del>-from twisted.plugin import IPlugin
-from twisted.internet.defer import gatherResults, Deferred, inlineCallbacks, succeed
-from twisted.internet.process import ProcessExitedAlready
-from twisted.internet.protocol import Protocol, Factory
-from twisted.internet.protocol import ProcessProtocol
-from twisted.internet.endpoints import UNIXClientEndpoint, TCP4ClientEndpoint
-from twisted.application.internet import TCPServer, UNIXServer
-from twisted.application.service import MultiService, IServiceMaker
-from twisted.application.service import Service
-from twisted.protocols.amp import AMP
</del><span class="cx"> 
</span><del>-from txweb2.server import Site
-from twext.python.log import Logger, LogLevel, replaceTwistedLoggers
-from twext.python.filepath import CachingFilePath
</del><ins>+from twext.enterprise.adbapi2 import ConnectionPool
+from twext.enterprise.ienterprise import ORACLE_DIALECT
+from twext.enterprise.ienterprise import POSTGRES_DIALECT
+from twext.enterprise.queue import NonPerformingQueuer
+from twext.enterprise.queue import PeerConnectionPool
+from twext.enterprise.queue import WorkerFactory as QueueWorkerFactory
+from twext.internet.fswatch import DirectoryChangeListener, IDirectoryChangeListenee
</ins><span class="cx"> from twext.internet.ssl import ChainingOpenSSLContextFactory
</span><span class="cx"> from twext.internet.tcp import MaxAcceptTCPServer, MaxAcceptSSLServer
</span><del>-from twext.internet.fswatch import DirectoryChangeListener, IDirectoryChangeListenee
</del><ins>+from twext.python.filepath import CachingFilePath
+from twext.python.log import Logger, LogLevel, replaceTwistedLoggers
</ins><span class="cx"> from txweb2.channel.http import LimitingHTTPFactory, SSLRedirectRequest, \
</span><span class="cx">     HTTPChannel
</span><span class="cx"> from txweb2.metafd import ConnectionLimiter, ReportingHTTPService
</span><del>-from twext.enterprise.ienterprise import POSTGRES_DIALECT
-from twext.enterprise.ienterprise import ORACLE_DIALECT
-from twext.enterprise.adbapi2 import ConnectionPool
-from twext.enterprise.queue import NonPerformingQueuer
-from twext.enterprise.queue import PeerConnectionPool
-from twext.enterprise.queue import WorkerFactory as QueueWorkerFactory
</del><ins>+from txweb2.server import Site
</ins><span class="cx"> 
</span><ins>+from txdav.caldav.datastore.scheduling.imip.inbound import MailRetriever
+from txdav.caldav.datastore.scheduling.imip.inbound import scheduleNextMailPoll
</ins><span class="cx"> from txdav.common.datastore.sql_tables import schema
</span><ins>+from txdav.common.datastore.upgrade.migrate import UpgradeToDatabaseStep
</ins><span class="cx"> from txdav.common.datastore.upgrade.sql.upgrade import (
</span><ins>+    UpgradeDatabaseCalendarDataStep, UpgradeDatabaseOtherStep,
</ins><span class="cx">     UpgradeDatabaseSchemaStep, UpgradeDatabaseAddressBookDataStep,
</span><del>-    UpgradeDatabaseCalendarDataStep, UpgradeDatabaseOtherStep,
</del><span class="cx">     UpgradeAcquireLockStep, UpgradeReleaseLockStep, UpgradeDatabaseNotificationDataStep)
</span><del>-from txdav.common.datastore.upgrade.migrate import UpgradeToDatabaseStep
-from txdav.caldav.datastore.scheduling.imip.inbound import MailRetriever
-from txdav.caldav.datastore.scheduling.imip.inbound import scheduleNextMailPoll
</del><ins>+from txdav.common.datastore.work.revision_cleanup import scheduleFirstFindMinRevision
</ins><span class="cx"> 
</span><ins>+from twistedcaldav import memcachepool
</ins><span class="cx"> from twistedcaldav.config import config, ConfigurationError
</span><del>-from twistedcaldav.stdconfig import DEFAULT_CONFIG, DEFAULT_CONFIG_FILE
</del><span class="cx"> from twistedcaldav.directory import calendaruserproxy
</span><span class="cx"> from twistedcaldav.directory.directory import GroupMembershipCacheUpdater
</span><ins>+from twistedcaldav.directory.directory import scheduleNextGroupCachingUpdate
</ins><span class="cx"> from twistedcaldav.localization import processLocalizationFiles
</span><del>-from twistedcaldav import memcachepool
</del><ins>+from twistedcaldav.stdconfig import DEFAULT_CONFIG, DEFAULT_CONFIG_FILE
</ins><span class="cx"> from twistedcaldav.upgrade import UpgradeFileSystemFormatStep, PostDBImportStep
</span><del>-from twistedcaldav.directory.directory import scheduleNextGroupCachingUpdate
</del><span class="cx"> 
</span><span class="cx"> try:
</span><span class="cx">     from twistedcaldav.authkerb import NegotiateCredentialFactory
</span><span class="lines">@@ -92,22 +93,22 @@
</span><span class="cx"> except ImportError:
</span><span class="cx">     NegotiateCredentialFactory = None
</span><span class="cx"> 
</span><del>-from calendarserver.tap.util import pgServiceFromConfig, getDBPool, MemoryLimitService
-from calendarserver.tap.util import checkDirectories
-from calendarserver.tap.util import Stepper
-from calendarserver.tap.util import ConnectionDispenser
-from calendarserver.tap.util import getRootResource
-from calendarserver.tap.util import storeFromConfig
-from calendarserver.tap.util import pgConnectorFromConfig
-from calendarserver.tap.util import oracleConnectorFromConfig
-from calendarserver.controlsocket import ControlSocket
-from calendarserver.controlsocket import ControlSocketConnectingService
</del><span class="cx"> from calendarserver.accesslog import AMPCommonAccessLoggingObserver
</span><span class="cx"> from calendarserver.accesslog import AMPLoggingFactory
</span><span class="cx"> from calendarserver.accesslog import RotatingFileAccessLoggingObserver
</span><del>-from calendarserver.push.notifier import PushDistributor
</del><ins>+from calendarserver.controlsocket import ControlSocket
+from calendarserver.controlsocket import ControlSocketConnectingService
</ins><span class="cx"> from calendarserver.push.amppush import AMPPushMaster, AMPPushForwarder
</span><span class="cx"> from calendarserver.push.applepush import ApplePushNotifierService
</span><ins>+from calendarserver.push.notifier import PushDistributor
+from calendarserver.tap.util import ConnectionDispenser
+from calendarserver.tap.util import Stepper
+from calendarserver.tap.util import checkDirectories
+from calendarserver.tap.util import getRootResource
+from calendarserver.tap.util import oracleConnectorFromConfig
+from calendarserver.tap.util import pgConnectorFromConfig
+from calendarserver.tap.util import pgServiceFromConfig, getDBPool, MemoryLimitService
+from calendarserver.tap.util import storeFromConfig
</ins><span class="cx"> 
</span><span class="cx"> try:
</span><span class="cx">     from calendarserver.version import version
</span><span class="lines">@@ -550,6 +551,7 @@
</span><span class="cx">             yield scheduleNextMailPoll(self.store, int(config.LogID) if config.LogID else 5)
</span><span class="cx">         if self.doGroupCaching:
</span><span class="cx">             yield scheduleNextGroupCachingUpdate(self.store, int(config.LogID) if config.LogID else 5)
</span><ins>+        yield scheduleFirstFindMinRevision(self.store)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> 
</span></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstwistedcaldavstdconfigpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/twistedcaldav/stdconfig.py (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/twistedcaldav/stdconfig.py        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/twistedcaldav/stdconfig.py        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -625,7 +625,9 @@
</span><span class="cx"> 
</span><span class="cx">     &quot;RemoveDuplicatePrivateComments&quot;: False, # Remove duplicate private comments on PUT
</span><span class="cx"> 
</span><del>-    &quot;SyncTokenLifetimeDays&quot; : 14, # Number of days that a client sync report token is valid
</del><ins>+    &quot;SyncTokenLifetimeDays&quot; : 16,       # Number of days that a client sync report token is valid
+    &quot;RevisionCleanupPeriodDays&quot; : 2,    # Number of days between revision cleanups
+    &quot;RevisionCleanupPhaseDays&quot; : 0.25,  # Number of days between startup and the first revision cleanup
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     # CardDAV Features
</span></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcarddavdatastoresqlpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/txdav/carddav/datastore/sql.py (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/carddav/datastore/sql.py        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/carddav/datastore/sql.py        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -569,15 +569,14 @@
</span><span class="cx"> 
</span><span class="cx">         if revision:
</span><span class="cx">             cs = schema.CALENDARSERVER
</span><del>-            minRevisionRows = yield Select(
</del><ins>+            minRevision = int((yield Select(
</ins><span class="cx">                 [cs.VALUE],
</span><span class="cx">                 From=cs,
</span><span class="cx">                 Where=(cs.NAME == &quot;MIN-REVISION&quot;)
</span><del>-            ).on(self._txn)
</del><ins>+            ).on(self._txn))[0][0])
</ins><span class="cx"> 
</span><del>-            if minRevisionRows:
-                if revision &lt; int(minRevisionRows[0][0]):
-                    raise SyncTokenValidException
</del><ins>+            if revision &lt; minRevision:
+                raise SyncTokenValidException
</ins><span class="cx"> 
</span><span class="cx">         # call sharedChildResourceNamesSinceRevision() and filter results
</span><span class="cx">         sharedChildChanged, sharedChildDeleted = yield self.sharedChildResourceNamesSinceRevision(revision, &quot;infinity&quot;)
</span><span class="lines">@@ -2345,7 +2344,7 @@
</span><span class="cx">         return Delete(
</span><span class="cx">             aboMembers,
</span><span class="cx">             Where=(aboMembers.GROUP_ID.In(Parameter(&quot;groupIDs&quot;, len(groupIDs)))).And(
</span><del>-                aboMembers.GROUP_ID.In(Parameter(&quot;memberIDs&quot;, len(memberIDs)))).And(
</del><ins>+                aboMembers.MEMBER_ID.In(Parameter(&quot;memberIDs&quot;, len(memberIDs)))).And(
</ins><span class="cx">                     aboMembers.REVISION &lt; Parameter(&quot;revision&quot;)
</span><span class="cx">                 )
</span><span class="cx">         )
</span></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresqlpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql.py (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql.py        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql.py        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -2035,15 +2035,14 @@
</span><span class="cx">         deleted = set()
</span><span class="cx">         if revision:
</span><span class="cx">             cs = schema.CALENDARSERVER
</span><del>-            minRevisionRows = yield Select(
</del><ins>+            minRevision = int((yield Select(
</ins><span class="cx">                 [cs.VALUE],
</span><span class="cx">                 From=cs,
</span><span class="cx">                 Where=(cs.NAME == &quot;MIN-REVISION&quot;)
</span><del>-            ).on(self._txn)
</del><ins>+            ).on(self._txn))[0][0])
</ins><span class="cx"> 
</span><del>-            if minRevisionRows:
-                if revision &lt; int(minRevisionRows[0][0]):
-                    raise SyncTokenValidException
</del><ins>+            if revision &lt; minRevision:
+                raise SyncTokenValidException
</ins><span class="cx"> 
</span><span class="cx">             results = [
</span><span class="cx">                 (
</span><span class="lines">@@ -2479,15 +2478,14 @@
</span><span class="cx">         deleted = []
</span><span class="cx">         if revision:
</span><span class="cx">             cs = schema.CALENDARSERVER
</span><del>-            minRevisionRows = yield Select(
</del><ins>+            minRevision = int((yield Select(
</ins><span class="cx">                 [cs.VALUE],
</span><span class="cx">                 From=cs,
</span><span class="cx">                 Where=(cs.NAME == &quot;MIN-REVISION&quot;)
</span><del>-            ).on(self._txn)
</del><ins>+            ).on(self._txn))[0][0])
</ins><span class="cx"> 
</span><del>-            if minRevisionRows:
-                if revision &lt; int(minRevisionRows[0][0]):
-                    raise SyncTokenValidException
</del><ins>+            if revision &lt; minRevision:
+                raise SyncTokenValidException
</ins><span class="cx"> 
</span><span class="cx">             results = [
</span><span class="cx">                 (name if name else &quot;&quot;, removed) for name, removed in
</span><span class="lines">@@ -6207,3 +6205,66 @@
</span><span class="cx">         # obscure bug.
</span><span class="cx">     else:
</span><span class="cx">         yield t.commit()
</span><ins>+
+
+
+@inlineCallbacks
+def deleteRevisionsBefore(txn, minRevision):
+    &quot;&quot;&quot;
+    Delete revisions before minRevision
+    &quot;&quot;&quot;
+    # Delete old revisions
+    for table in (
+        schema.CALENDAR_OBJECT_REVISIONS,
+        schema.NOTIFICATION_OBJECT_REVISIONS,
+        schema.ADDRESSBOOK_OBJECT_REVISIONS,
+    ):
+        yield Delete(
+            From=table,
+            Where=(table.REVISION &lt; minRevision)
+        ).on(txn)
+
+    # get groups where this object was once a member and version info
+    aboMembers = schema.ABO_MEMBERS
+    groupRows = yield Select([aboMembers.GROUP_ID, aboMembers.MEMBER_ID, aboMembers.DELETED, aboMembers.REVISION],
+        From=aboMembers,
+    ).on(txn)
+
+    # group results by group, member, and revisionInfo
+    groupIDToMemberIDMap = {}
+    for groupRow in groupRows:
+        groupID, memberID, deleted, revision = groupRow
+        revisionInfo = [deleted, revision]
+        if groupID not in groupIDToMemberIDMap:
+            groupIDToMemberIDMap[groupID] = {}
+        memberIDToRevisionsMap = groupIDToMemberIDMap[groupID]
+        if memberID not in memberIDToRevisionsMap:
+            memberIDToRevisionsMap[memberID] = []
+        revisionInfoList = memberIDToRevisionsMap[memberID]
+        revisionInfoList.append(revisionInfo)
+
+    # go though list an delete old revisions, leaving at least one undeleted member
+    for groupID, memberIDToRevisionsMap in groupIDToMemberIDMap.iteritems():
+        for memberID, revisionInfoList in memberIDToRevisionsMap.iteritems():
+
+            revisionsToRemove = []
+            maxRevisionInfoToRemove = None
+            revisionsToSave = []
+            for revisionInfo in revisionInfoList:
+                deleted, revision = revisionInfo
+                if revision &lt; minRevision:
+                    revisionsToRemove.append(revision)
+                    if not maxRevisionInfoToRemove or revision &gt; maxRevisionInfoToRemove[1]:
+                        maxRevisionInfoToRemove = revisionInfo
+                else:
+                    revisionsToSave.append(revision)
+
+            if revisionsToRemove and (revisionsToSave or maxRevisionInfoToRemove[0]):
+                aboMembers = schema.ABO_MEMBERS
+                yield Delete(
+                    aboMembers,
+                    Where=(aboMembers.GROUP_ID == groupID).And(
+                        aboMembers.MEMBER_ID == memberID).And(
+                            aboMembers.REVISION.In(revisionsToRemove)
+                        )
+                )
</ins></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemacurrentoracledialectsql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current-oracle-dialect.sql (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current-oracle-dialect.sql        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current-oracle-dialect.sql        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -372,6 +372,11 @@
</span><span class="cx">     &quot;RESOURCE_ID&quot; integer not null references CALENDAR_OBJECT on delete cascade
</span><span class="cx"> );
</span><span class="cx"> 
</span><ins>+create table REVISION_CLEANUP_WORK (
+    &quot;WORK_ID&quot; integer primary key not null,
+    &quot;NOT_BEFORE&quot; timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);
+
</ins><span class="cx"> create table CALENDARSERVER (
</span><span class="cx">     &quot;NAME&quot; nvarchar2(255) primary key,
</span><span class="cx">     &quot;VALUE&quot; nvarchar2(255)
</span></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemacurrentsql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current.sql (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current.sql        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/current.sql        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -706,6 +706,15 @@
</span><span class="cx"> create index CALENDAR_OBJECT_SPLITTER_WORK_RESOURCE_ID on
</span><span class="cx">         CALENDAR_OBJECT_SPLITTER_WORK(RESOURCE_ID);
</span><span class="cx"> 
</span><ins>+---------------------------
+-- Revision Cleaner Work --
+---------------------------
+
+create table REVISION_CLEANUP_WORK (
+  WORK_ID                       integer      primary key default nextval('WORKITEM_SEQ') not null, -- implicit index
+  NOT_BEFORE                    timestamp    default timezone('UTC', CURRENT_TIMESTAMP)
+);
+
</ins><span class="cx"> --------------------
</span><span class="cx"> -- Schema Version --
</span><span class="cx"> --------------------
</span></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemaupgradesoracledialectupgrade_from_30_to_31sql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_30_to_31.sql (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_30_to_31.sql        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_30_to_31.sql        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -29,7 +29,13 @@
</span><span class="cx"> alter table NOTIFICATION_OBJECT_REVISIONS
</span><span class="cx">  add (&quot;MODIFIED&quot; timestamp default CURRENT_TIMESTAMP at time zone 'UTC');
</span><span class="cx"> 
</span><ins>+ -- Add cleanup work table --
</ins><span class="cx">  
</span><ins>+create table REVISION_CLEANUP_WORK (
+  &quot;WORK_ID&quot; integer primary key not null,
+  &quot;NOT_BEFORE&quot; timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);

</ins><span class="cx"> -- Update version --
</span><span class="cx"> 
</span><span class="cx"> update CALENDARSERVER set VALUE = '31' where NAME = 'VERSION';
</span></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoresql_schemaupgradespostgresdialectupgrade_from_30_to_31sql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_30_to_31.sql (12181 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_30_to_31.sql        2013-12-21 00:38:11 UTC (rev 12181)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_30_to_31.sql        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -29,6 +29,12 @@
</span><span class="cx"> alter table NOTIFICATION_OBJECT_REVISIONS
</span><span class="cx">   add column MODIFIED timestamp default timezone('UTC', CURRENT_TIMESTAMP);
</span><span class="cx"> 
</span><ins>+ -- Add cleanup work table --

+create table REVISION_CLEANUP_WORK (
+  &quot;WORK_ID&quot; integer primary key not null,
+  &quot;NOT_BEFORE&quot; timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);
</ins><span class="cx">   
</span><span class="cx"> -- Update version --
</span><span class="cx"> 
</span></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastorework__init__py"></a>
<div class="addfile"><h4>Added: CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/__init__.py (0 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/__init__.py                                (rev 0)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/__init__.py        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -0,0 +1,19 @@
</span><ins>+##
+# Copyright (c) 2005-2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# 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 &quot;AS IS&quot; 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.
+##
+
+&quot;&quot;&quot;
+Common work items
+&quot;&quot;&quot;
</ins></span></pre></div>
<a id="CalendarServerbranchesusersgayacleanrevisionstxdavcommondatastoreworkrevision_cleanuppy"></a>
<div class="addfile"><h4>Added: CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/revision_cleanup.py (0 => 12182)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/revision_cleanup.py                                (rev 0)
+++ CalendarServer/branches/users/gaya/cleanrevisions/txdav/common/datastore/work/revision_cleanup.py        2013-12-21 04:32:24 UTC (rev 12182)
</span><span class="lines">@@ -0,0 +1,143 @@
</span><ins>+# -*- test-case-name: twext.who.test.test_groups -*-
+##
+# Copyright (c) 2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# 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 &quot;AS IS&quot; 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.
+##
+
+&quot;&quot;&quot;
+Remove old and unused REVISION rows
+&quot;&quot;&quot;
+
+from twext.enterprise.dal.record import fromTable
+from twext.enterprise.dal.syntax import Delete, Select, Update, Max
+from twext.enterprise.queue import WorkItem
+from twext.python.log import Logger
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twistedcaldav.config import config
+from txdav.common.datastore.sql import deleteRevisionsBefore
+from txdav.common.datastore.sql_tables import schema
+import datetime
+
+log = Logger()
+
+
+class FindMinRevisionWork(WorkItem,
+    fromTable(schema.REVISION_CLEANUP_WORK)):
+
+    group = &quot;find_min_revision&quot;
+
+    @inlineCallbacks
+    def doWork(self):
+
+        # Delete all other work items
+        yield Delete(From=self.table, Where=None).on(self.transaction)
+
+        # Get the minimum valid revision
+        cs = schema.CALENDARSERVER
+        minRevision = int((yield Select(
+            [cs.VALUE],
+            From=cs,
+            Where=(cs.NAME == &quot;MIN-REVISION&quot;)
+        ).on(self.transaction))[0][0])
+
+        # get max revision on table rows before dateLimit
+        dateLimit = (datetime.datetime.utcnow() -
+            datetime.timedelta(days=float(config.SyncTokenLifetimeDays)))
+        maxRevision = 0
+
+        # TODO: Use one Select statement
+        for table in (
+            schema.CALENDAR_OBJECT_REVISIONS,
+            schema.NOTIFICATION_OBJECT_REVISIONS,
+            schema.ADDRESSBOOK_OBJECT_REVISIONS,
+            schema.ABO_MEMBERS,
+        ):
+            revisionRows = yield Select(
+                [Max(table.REVISION)],
+                From=Select(
+                    [table.REVISION],
+                    From=table,
+                    Where=(table.MODIFIED &lt; dateLimit),
+                ).on(self.transaction)
+            )
+            if revisionRows:
+                tableMaxRevision = revisionRows[0][0]
+                if tableMaxRevision &gt; maxRevision:
+                    maxRevison = tableMaxRevision
+
+        if maxRevision &gt; minRevision:
+            # save it
+            cs = schema.CALENDARSERVER
+            yield Update(
+                {cs.VALUE: minRevision},
+                Where=cs.NAME == &quot;MIN-REVISION&quot;,
+            ).on(self.transaction)
+
+            # Schedule revision cleanup
+            notBefore = (datetime.datetime.utcnow() +
+                datetime.timedelta(seconds=10))
+            log.debug(&quot;Scheduling revision cleanup: %s&quot; % (notBefore,))
+            yield self.transaction.enqueue(RevisionCleanupWork,
+                notBefore=notBefore)
+
+        else:
+            # Schedule next update
+            notBefore = (datetime.datetime.utcnow() +
+                datetime.timedelta(days=float(config.RevisionCleanupPeriodDays)))
+            log.debug(&quot;Rescheduling find minimum revision work: %s&quot; % (notBefore,))
+            yield self.transaction.enqueue(FindMinRevisionWork,
+                notBefore=notBefore)
+
+
+
+class RevisionCleanupWork(WorkItem,
+    fromTable(schema.REVISION_CLEANUP_WORK)):
+
+    group = &quot;group_revsion_cleanup&quot;
+
+    @inlineCallbacks
+    def doWork(self):
+
+        # Delete all other work items
+        yield Delete(From=self.table, Where=None).on(self.transaction)
+
+        # Get the minimum valid revision
+        cs = schema.CALENDARSERVER
+        minRevision = int((yield Select(
+            [cs.VALUE],
+            From=cs,
+            Where=(cs.NAME == &quot;MIN-REVISION&quot;)
+        ).on(self.transaction))[0][0])
+
+        # delete revisions
+        yield deleteRevisionsBefore(self.transaction, minRevision)
+
+        # Schedule next update
+        notBefore = (datetime.datetime.utcnow() +
+            datetime.timedelta(days=float(config.RevisionCleanupPeriodDays)))
+        log.debug(&quot;Rescheduling find minimum revision work: %s&quot; % (notBefore,))
+        yield self.transaction.enqueue(FindMinRevisionWork,
+            notBefore=notBefore)
+
+
+
+@inlineCallbacks
+def scheduleFirstFindMinRevision(store):
+    txn = store.newTransaction()
+    notBefore = (datetime.datetime.utcnow() +
+        datetime.timedelta(days=float(config.RevisionCleanupPhaseDays)))
+    log.debug(&quot;Scheduling find minimum revision work: %s&quot; % (notBefore,))
+    wp = (yield txn.enqueue(FindMinRevisionWork, notBefore=notBefore))
+    yield txn.commit()
+    returnValue(wp)
</ins></span></pre>
</div>
</div>

</body>
</html>