You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by jo...@apache.org on 2010/12/21 23:17:12 UTC

svn commit: r1051679 [4/6] - in /cassandra/trunk: ./ conf/ interface/ interface/thrift/gen-java/org/apache/cassandra/thrift/ src/java/org/apache/cassandra/avro/ src/java/org/apache/cassandra/concurrent/ src/java/org/apache/cassandra/config/ src/java/or...

Modified: cassandra/trunk/src/java/org/apache/cassandra/concurrent/Stage.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/concurrent/Stage.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/concurrent/Stage.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/concurrent/Stage.java Tue Dec 21 22:17:09 2010
@@ -31,7 +31,8 @@ public enum Stage
     ANTI_ENTROPY,
     MIGRATION,
     MISC,
-    INTERNAL_RESPONSE;
+    INTERNAL_RESPONSE,
+    REPLICATE_ON_WRITE;
 
     public String getJmxType()
     {
@@ -47,6 +48,7 @@ public enum Stage
             case MUTATION:
             case READ:
             case REQUEST_RESPONSE:
+            case REPLICATE_ON_WRITE:
                 return "request";
             default:
                 throw new AssertionError("Unknown stage " + this);

Modified: cassandra/trunk/src/java/org/apache/cassandra/concurrent/StageManager.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/concurrent/StageManager.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/concurrent/StageManager.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/concurrent/StageManager.java Tue Dec 21 22:17:09 2010
@@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit;
 
 import static org.apache.cassandra.config.DatabaseDescriptor.getConcurrentReaders;
 import static org.apache.cassandra.config.DatabaseDescriptor.getConcurrentWriters;
+import static org.apache.cassandra.config.DatabaseDescriptor.getConcurrentReplicators;
 
 
 /**
@@ -44,6 +45,7 @@ public class StageManager
         stages.put(Stage.READ, multiThreadedConfigurableStage(Stage.READ, getConcurrentReaders()));        
         stages.put(Stage.REQUEST_RESPONSE, multiThreadedStage(Stage.REQUEST_RESPONSE, Math.max(2, Runtime.getRuntime().availableProcessors())));
         stages.put(Stage.INTERNAL_RESPONSE, multiThreadedStage(Stage.INTERNAL_RESPONSE, Math.max(2, Runtime.getRuntime().availableProcessors())));
+        stages.put(Stage.REPLICATE_ON_WRITE, multiThreadedConfigurableStage(Stage.REPLICATE_ON_WRITE, getConcurrentReplicators()));
         // the rest are all single-threaded
         stages.put(Stage.STREAM, new JMXEnabledThreadPoolExecutor(Stage.STREAM));
         stages.put(Stage.GOSSIP, new JMXEnabledThreadPoolExecutor(Stage.GOSSIP));

Modified: cassandra/trunk/src/java/org/apache/cassandra/config/CFMetaData.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/config/CFMetaData.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/config/CFMetaData.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/config/CFMetaData.java Tue Dec 21 22:17:09 2010
@@ -58,6 +58,7 @@ public final class CFMetaData
     public final static double DEFAULT_ROW_CACHE_SIZE = 0.0;
     public final static double DEFAULT_KEY_CACHE_SIZE = 200000;
     public final static double DEFAULT_READ_REPAIR_CHANCE = 1.0;
+    public final static boolean DEFAULT_REPLICATE_ON_WRITE = true;
     public final static int DEFAULT_ROW_CACHE_SAVE_PERIOD_IN_SECONDS = 0;
     public final static int DEFAULT_KEY_CACHE_SAVE_PERIOD_IN_SECONDS = 3600;
     public final static int DEFAULT_GC_GRACE_SECONDS = 864000;
@@ -90,6 +91,7 @@ public final class CFMetaData
                               0,
                               0.01,
                               0,
+                              false,
                               0,
                               BytesType.instance,
                               DEFAULT_MIN_COMPACTION_THRESHOLD,
@@ -155,6 +157,7 @@ public final class CFMetaData
     private double rowCacheSize;                      // default 0
     private double keyCacheSize;                      // default 0.01
     private double readRepairChance;                  // default 1.0 (always), chance [0.0,1.0] of read repair
+    private boolean replicateOnWrite;                 // default false
     private int gcGraceSeconds;                       // default 864000 (ten days)
     private AbstractType defaultValidator;            // default none, use comparator types
     private Integer minCompactionThreshold;           // default 4
@@ -177,6 +180,7 @@ public final class CFMetaData
                        double rowCacheSize,
                        double keyCacheSize,
                        double readRepairChance,
+                       boolean replicateOnWrite,
                        int gcGraceSeconds,
                        AbstractType defaultValidator,
                        int minCompactionThreshold,
@@ -204,6 +208,7 @@ public final class CFMetaData
         this.rowCacheSize = rowCacheSize;
         this.keyCacheSize = keyCacheSize;
         this.readRepairChance = readRepairChance;
+        this.replicateOnWrite = replicateOnWrite;
         this.gcGraceSeconds = gcGraceSeconds;
         this.defaultValidator = defaultValidator;
         this.minCompactionThreshold = minCompactionThreshold;
@@ -242,6 +247,7 @@ public final class CFMetaData
                       double rowCacheSize,
                       double keyCacheSize,
                       double readRepairChance,
+                      boolean replicateOnWrite,
                       int gcGraceSeconds,
                       AbstractType defaultValidator,
                       int minCompactionThreshold,
@@ -263,6 +269,7 @@ public final class CFMetaData
              rowCacheSize,
              keyCacheSize,
              readRepairChance,
+             replicateOnWrite,
              gcGraceSeconds,
              defaultValidator,
              minCompactionThreshold,
@@ -287,6 +294,7 @@ public final class CFMetaData
                               0,
                               0,
                               0,
+                              false,
                               DEFAULT_GC_GRACE_SECONDS,
                               BytesType.instance,
                               DEFAULT_MIN_COMPACTION_THRESHOLD,
@@ -311,6 +319,7 @@ public final class CFMetaData
                               cfm.rowCacheSize,
                               cfm.keyCacheSize,
                               cfm.readRepairChance,
+                              cfm.replicateOnWrite,
                               cfm.gcGraceSeconds,
                               cfm.defaultValidator,
                               cfm.minCompactionThreshold,
@@ -336,6 +345,7 @@ public final class CFMetaData
                               cfm.rowCacheSize,
                               cfm.keyCacheSize,
                               cfm.readRepairChance,
+                              cfm.replicateOnWrite,
                               cfm.gcGraceSeconds,
                               cfm.defaultValidator,
                               cfm.minCompactionThreshold,
@@ -369,6 +379,7 @@ public final class CFMetaData
         cf.row_cache_size = rowCacheSize;
         cf.key_cache_size = keyCacheSize;
         cf.read_repair_chance = readRepairChance;
+        cf.replicate_on_write = replicateOnWrite;
         cf.gc_grace_seconds = gcGraceSeconds;
         cf.default_validation_class = new Utf8(defaultValidator.getClass().getName());
         cf.min_compaction_threshold = minCompactionThreshold;
@@ -428,6 +439,7 @@ public final class CFMetaData
                               cf.row_cache_size,
                               cf.key_cache_size,
                               cf.read_repair_chance,
+                              cf.replicate_on_write,
                               cf.gc_grace_seconds,
                               validator,
                               minct,
@@ -460,6 +472,11 @@ public final class CFMetaData
     {
         return readRepairChance;
     }
+
+    public boolean getReplicateOnWrite()
+    {
+        return replicateOnWrite;
+    }
     
     public int getGcGraceSeconds()
     {
@@ -533,6 +550,7 @@ public final class CFMetaData
             .append(rowCacheSize, rhs.rowCacheSize)
             .append(keyCacheSize, rhs.keyCacheSize)
             .append(readRepairChance, rhs.readRepairChance)
+            .append(replicateOnWrite, rhs.replicateOnWrite)
             .append(gcGraceSeconds, rhs.gcGraceSeconds)
             .append(minCompactionThreshold, rhs.minCompactionThreshold)
             .append(maxCompactionThreshold, rhs.maxCompactionThreshold)
@@ -558,6 +576,7 @@ public final class CFMetaData
             .append(rowCacheSize)
             .append(keyCacheSize)
             .append(readRepairChance)
+            .append(replicateOnWrite)
             .append(gcGraceSeconds)
             .append(defaultValidator)
             .append(minCompactionThreshold)
@@ -654,6 +673,7 @@ public final class CFMetaData
         rowCacheSize = cf_def.row_cache_size;
         keyCacheSize = cf_def.key_cache_size;
         readRepairChance = cf_def.read_repair_chance;
+        replicateOnWrite = cf_def.replicate_on_write;
         gcGraceSeconds = cf_def.gc_grace_seconds;
         defaultValidator = DatabaseDescriptor.getComparator(cf_def.default_validation_class);
         minCompactionThreshold = cf_def.min_compaction_threshold;
@@ -716,6 +736,7 @@ public final class CFMetaData
         def.setRow_cache_size(cfm.rowCacheSize);
         def.setKey_cache_size(cfm.keyCacheSize);
         def.setRead_repair_chance(cfm.readRepairChance);
+        def.setReplicate_on_write(cfm.replicateOnWrite);
         def.setGc_grace_seconds(cfm.gcGraceSeconds);
         def.setDefault_validation_class(cfm.defaultValidator.getClass().getName());
         def.setMin_compaction_threshold(cfm.minCompactionThreshold);
@@ -757,6 +778,7 @@ public final class CFMetaData
         def.row_cache_size = cfm.rowCacheSize;
         def.key_cache_size = cfm.keyCacheSize;
         def.read_repair_chance = cfm.readRepairChance;
+        def.replicate_on_write = cfm.replicateOnWrite;
         def.gc_grace_seconds = cfm.gcGraceSeconds;
         def.default_validation_class = cfm.defaultValidator == null ? null : cfm.defaultValidator.getClass().getName();
         def.min_compaction_threshold = cfm.minCompactionThreshold;
@@ -799,6 +821,7 @@ public final class CFMetaData
         newDef.memtable_throughput_in_mb = def.getMemtable_throughput_in_mb();
         newDef.min_compaction_threshold = def.getMin_compaction_threshold();
         newDef.read_repair_chance = def.getRead_repair_chance();
+        newDef.replicate_on_write = def.isReplicate_on_write();
         newDef.row_cache_save_period_in_seconds = def.getRow_cache_save_period_in_seconds();
         newDef.row_cache_size = def.getRow_cache_size();
         newDef.subcomparator_type = def.getSubcomparator_type();
@@ -917,6 +940,7 @@ public final class CFMetaData
             .append("rowCacheSize", rowCacheSize)
             .append("keyCacheSize", keyCacheSize)
             .append("readRepairChance", readRepairChance)
+            .append("replicateOnWrite", replicateOnWrite)
             .append("gcGraceSeconds", gcGraceSeconds)
             .append("defaultValidator", defaultValidator)
             .append("minCompactionThreshold", minCompactionThreshold)

Modified: cassandra/trunk/src/java/org/apache/cassandra/config/Config.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/config/Config.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/config/Config.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/config/Config.java Tue Dec 21 22:17:09 2010
@@ -53,6 +53,7 @@ public class Config
     
     public Integer concurrent_reads = 8;
     public Integer concurrent_writes = 32;
+    public Integer concurrent_replicates = 32;
     
     public Integer memtable_flush_writers = null; // will get set to the length of data dirs in DatabaseDescriptor
     

Modified: cassandra/trunk/src/java/org/apache/cassandra/config/DatabaseDescriptor.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/config/DatabaseDescriptor.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/config/DatabaseDescriptor.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/config/DatabaseDescriptor.java Tue Dec 21 22:17:09 2010
@@ -224,6 +224,11 @@ public class    DatabaseDescriptor
                 throw new ConfigurationException("concurrent_writes must be at least 2");
             }
 
+            if (conf.concurrent_replicates != null && conf.concurrent_replicates < 2)
+            {
+                throw new ConfigurationException("conf.concurrent_replicates must be at least 2");
+            }
+
             /* Memtable flush writer threads */
             if (conf.memtable_flush_writers != null && conf.memtable_flush_writers < 1)
             {
@@ -613,6 +618,7 @@ public class    DatabaseDescriptor
                                              cf.rows_cached,
                                              cf.keys_cached, 
                                              cf.read_repair_chance,
+                                             cf.replicate_on_write,
                                              cf.gc_grace_seconds,
                                              default_validator,
                                              cf.min_compaction_threshold,
@@ -841,6 +847,11 @@ public class    DatabaseDescriptor
         return conf.concurrent_writes;
     }
 
+    public static int getConcurrentReplicators()
+    {
+        return conf.concurrent_replicates;
+    }
+
     public static int getFlushWriters()
     {
             return conf.memtable_flush_writers;

Modified: cassandra/trunk/src/java/org/apache/cassandra/config/RawColumnFamily.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/config/RawColumnFamily.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/config/RawColumnFamily.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/config/RawColumnFamily.java Tue Dec 21 22:17:09 2010
@@ -36,6 +36,7 @@ public class RawColumnFamily
     public double rows_cached = CFMetaData.DEFAULT_ROW_CACHE_SIZE; 
     public double keys_cached = CFMetaData.DEFAULT_KEY_CACHE_SIZE; 
     public double read_repair_chance = CFMetaData.DEFAULT_READ_REPAIR_CHANCE;
+    public boolean replicate_on_write = CFMetaData.DEFAULT_REPLICATE_ON_WRITE;
     public int gc_grace_seconds = CFMetaData.DEFAULT_GC_GRACE_SECONDS;
     public String default_validation_class;
     public int min_compaction_threshold = CFMetaData.DEFAULT_MIN_COMPACTION_THRESHOLD;

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamily.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamily.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamily.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamily.java Tue Dec 21 22:17:09 2010
@@ -33,6 +33,7 @@ import org.apache.cassandra.config.CFMet
 import org.apache.cassandra.config.DatabaseDescriptor;
 import org.apache.cassandra.db.filter.QueryPath;
 import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.AbstractCommutativeType;
 import org.apache.cassandra.io.ICompactSerializer2;
 import org.apache.cassandra.io.util.IIterableColumns;
 import org.apache.cassandra.utils.FBUtilities;
@@ -154,18 +155,25 @@ public class ColumnFamily implements ICo
 
     public void addColumn(QueryPath path, ByteBuffer value, long timestamp)
     {
-        assert path.columnName != null : path;
-        addColumn(path.superColumnName, new Column(path.columnName, value, timestamp));
+        addColumn(path, value, timestamp, 0);
     }
 
     public void addColumn(QueryPath path, ByteBuffer value, long timestamp, int timeToLive)
     {
         assert path.columnName != null : path;
         Column column;
-        if (timeToLive > 0)
-            column = new ExpiringColumn(path.columnName, value, timestamp, timeToLive);
+        AbstractType defaultValidator = metadata().getDefaultValidator();
+        if (!defaultValidator.isCommutative())
+        {
+            if (timeToLive > 0)
+                column = new ExpiringColumn(path.columnName, value, timestamp, timeToLive);
+            else
+                column = new Column(path.columnName, value, timestamp);
+        }
         else
-            column = new Column(path.columnName, value, timestamp);
+        {
+            column = ((AbstractCommutativeType)defaultValidator).createColumn(path.columnName, value, timestamp);
+        }
         addColumn(path.superColumnName, column);
     }
 

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamilyStore.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamilyStore.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/ColumnFamilyStore.java Tue Dec 21 22:17:09 2010
@@ -25,6 +25,7 @@ import java.util.*;
 import java.util.concurrent.*;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
 import java.util.regex.Pattern;
 import javax.management.MBeanServer;
 import javax.management.ObjectName;
@@ -292,6 +293,42 @@ public class ColumnFamilyStore implement
         return keys;
     }
 
+    public boolean reverseReadWriteOrder()
+    {
+        //XXX: PURPOSE: allow less harmful race condition w/o locking
+
+        // normal read/write order (non-commutative):
+        //   purpose:
+        //     avoid missing an MT; may double reconcile
+        //   read path order:
+        //     1) live MT
+        //     2) MTs pending flush
+        //     3) SSTs
+        //   write path order: (live MT => MT pending flush)
+        //     1) add live MT to MTs pending flush
+        //     2) reset live MT
+        //   write path order: (MT pending flush => SST)
+        //     1) add SST
+        //     2) remove MT pending flush
+
+        // reversed read/write order (commutative):
+        //   purpose:
+        //     avoid over-counting an MT; may miss an MT
+        //   read path order:
+        //     1) SSTs
+        //     2) MTs pending flush
+        //     3) live MT
+        //   write path order: (live MT => MT pending flush)
+        //     1) save live MT
+        //     2) reset live MT
+        //     3) add saved MT to MTs pending flush
+        //   write path order: (MT pending flush => SST)
+        //     1) remove MT pending flush
+        //     2) add SST
+
+        return metadata.getDefaultValidator().isCommutative();
+    }
+
     public void addIndex(final ColumnDefinition info)
     {
         assert info.getIndexType() != null;
@@ -650,8 +687,19 @@ public class ColumnFamilyStore implement
             final CountDownLatch latch = new CountDownLatch(icc.size());
             for (ColumnFamilyStore cfs : icc)
             {
-                submitFlush(cfs.memtable, latch);
-                cfs.memtable = new Memtable(cfs);
+                if (!reverseReadWriteOrder())
+                {
+                    //XXX: race condition: may allow double reconcile; but never misses an MT
+                    submitFlush(cfs.memtable, latch);
+                    cfs.memtable = new Memtable(cfs);
+                }
+                else
+                {
+                    //XXX: race condition: may miss an MT, but no double counts
+                    Memtable pendingFlush = cfs.memtable;
+                    cfs.memtable = new Memtable(cfs);
+                    submitFlush(pendingFlush, latch);
+                }
             }
 
             // when all the memtables have been written, including for indexes, mark the flush in the commitlog header.
@@ -793,7 +841,6 @@ public class ColumnFamilyStore implement
             // remove columns if
             // (a) the column itself is tombstoned or
             // (b) the CF is tombstoned and the column is not newer than it
-            // (we split the test to avoid computing ClockRelationship if not necessary)
             if ((c.isMarkedForDelete() && c.getLocalDeletionTime() <= gcBefore)
                 || c.timestamp() <= cf.getMarkedForDeleteAt())
             {
@@ -1180,36 +1227,75 @@ public class ColumnFamilyStore implement
         {
             IColumnIterator iter;
 
-            /* add the current memtable */
-            iter = filter.getMemtableColumnIterator(getMemtableThreadSafe(), getComparator());
-            if (iter != null)
+            int sstablesToIterate = 0;
+            if (!reverseReadWriteOrder())
             {
-                returnCF.delete(iter.getColumnFamily());
-                    
-                iterators.add(iter);
-            }
+                //XXX: race condition: may allow double reconcile; but never misses an MT
 
-            /* add the memtables being flushed */
-            for (Memtable memtable : memtablesPendingFlush)
-            {
-                iter = filter.getMemtableColumnIterator(memtable, getComparator());
+                /* add the current memtable */
+                iter = filter.getMemtableColumnIterator(getMemtableThreadSafe(), getComparator());
                 if (iter != null)
                 {
                     returnCF.delete(iter.getColumnFamily());
                     iterators.add(iter);
                 }
-            }
 
-            /* add the SSTables on disk */
-            int sstablesToIterate = 0;
-            for (SSTableReader sstable : ssTables)
+                /* add the memtables being flushed */
+                for (Memtable memtable : memtablesPendingFlush)
+                {
+                    iter = filter.getMemtableColumnIterator(memtable, getComparator());
+                    if (iter != null)
+                    {
+                        returnCF.delete(iter.getColumnFamily());
+                        iterators.add(iter);
+                    }
+                }
+                
+                /* add the SSTables on disk */
+                for (SSTableReader sstable : ssTables)
+                {
+                    iter = filter.getSSTableColumnIterator(sstable);
+                    if (iter.getColumnFamily() != null)
+                    {
+                        returnCF.delete(iter.getColumnFamily());
+                        iterators.add(iter);
+                    }
+                    sstablesToIterate++;
+                }
+            }
+            else
             {
-                iter = filter.getSSTableColumnIterator(sstable);
-                if (iter.getColumnFamily() != null)
+                //XXX: race condition: may miss an MT, but no double counts
+
+                /* add the SSTables on disk */
+                for (SSTableReader sstable : ssTables)
+                {
+                    iter = filter.getSSTableColumnIterator(sstable);
+                    if (iter.getColumnFamily() != null)
+                    {
+                        returnCF.delete(iter.getColumnFamily());
+                        iterators.add(iter);
+                    }
+                    sstablesToIterate++;
+                }
+
+                /* add the memtables being flushed */
+                for (Memtable memtable : memtablesPendingFlush)
+                {
+                    iter = filter.getMemtableColumnIterator(memtable, getComparator());
+                    if (iter != null)
+                    {
+                        returnCF.delete(iter.getColumnFamily());
+                        iterators.add(iter);
+                    }
+                }
+
+                /* add the current memtable */
+                iter = filter.getMemtableColumnIterator(getMemtableThreadSafe(), getComparator());
+                if (iter != null)
                 {
                     returnCF.delete(iter.getColumnFamily());
                     iterators.add(iter);
-                    sstablesToIterate++;
                 }
             }
             recentSSTablesPerRead.add(sstablesToIterate);
@@ -1270,12 +1356,23 @@ public class ColumnFamilyStore implement
 
         QueryFilter filter = new QueryFilter(null, new QueryPath(columnFamily, superColumn, null), columnFilter);
         Collection<Memtable> memtables = new ArrayList<Memtable>();
-        memtables.add(getMemtableThreadSafe());
-        memtables.addAll(memtablesPendingFlush);
-
         Collection<SSTableReader> sstables = new ArrayList<SSTableReader>();
-        Iterables.addAll(sstables, ssTables);
 
+        if (!reverseReadWriteOrder())
+        {
+            //XXX: race condition: may allow double reconcile; but never misses an MT
+            memtables.add(getMemtableThreadSafe());
+            memtables.addAll(memtablesPendingFlush);
+            Iterables.addAll(sstables, ssTables);
+        }
+        else
+        {
+            //XXX: race condition: may miss an MT, but no double counts
+            Iterables.addAll(sstables, ssTables);
+            memtables.addAll(memtablesPendingFlush);
+            memtables.add(getMemtableThreadSafe());
+        }
+        
         RowIterator iterator = RowIteratorFactory.getIterator(memtables, sstables, startWith, stopAt, filter, getComparator(), this);
         int gcBefore = (int)(System.currentTimeMillis() / 1000) - metadata.getGcGraceSeconds();
 

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/ColumnSerializer.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/ColumnSerializer.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/ColumnSerializer.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/ColumnSerializer.java Tue Dec 21 22:17:09 2010
@@ -25,6 +25,7 @@ import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.IOException;
 import java.nio.ByteBuffer;
+import java.util.Arrays;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -35,9 +36,10 @@ import org.apache.cassandra.utils.FBUtil
 public class ColumnSerializer implements ICompactSerializer2<IColumn>
 {
     private static final Logger logger = LoggerFactory.getLogger(ColumnSerializer.class);
-
+    
     public final static int DELETION_MASK = 0x01;
     public final static int EXPIRATION_MASK = 0x02;
+    public final static int COUNTER_MASK    = 0x04;
 
     public void serialize(IColumn column, DataOutput dos)
     {
@@ -45,12 +47,21 @@ public class ColumnSerializer implements
         FBUtilities.writeShortByteArray(column.name(), dos);
         try
         {
-            if (column instanceof ExpiringColumn) {
-              dos.writeByte(EXPIRATION_MASK);
-              dos.writeInt(((ExpiringColumn) column).getTimeToLive());
-              dos.writeInt(column.getLocalDeletionTime());
-            } else {
-              dos.writeByte((column.isMarkedForDelete()) ? DELETION_MASK : 0);
+            if (column instanceof CounterColumn)
+            {
+                dos.writeByte(COUNTER_MASK);
+                dos.writeLong(((CounterColumn)column).timestampOfLastDelete());
+                FBUtilities.writeShortByteArray(ByteBuffer.wrap(((CounterColumn)column).partitionedCounter()), dos);
+            }
+            else if (column instanceof ExpiringColumn)
+            {
+                dos.writeByte(EXPIRATION_MASK);
+                dos.writeInt(((ExpiringColumn) column).getTimeToLive());
+                dos.writeInt(column.getLocalDeletionTime());
+            }
+            else
+            {
+                dos.writeByte((column.isMarkedForDelete()) ? DELETION_MASK : 0);
             }
             dos.writeLong(column.timestamp());
             FBUtilities.writeByteArray(column.value(), dos);
@@ -68,7 +79,16 @@ public class ColumnSerializer implements
             throw new CorruptColumnException("invalid column name length " + name.remaining());
 
         int b = dis.readUnsignedByte();
-        if ((b & EXPIRATION_MASK) != 0)
+        if ((b & COUNTER_MASK) != 0)
+        {
+            long timestampOfLastDelete = dis.readLong();
+            ByteBuffer pc = FBUtilities.readShortByteArray(dis);
+            byte[] partitionedCounter = Arrays.copyOfRange(pc.array(), pc.position() + pc.arrayOffset(), pc.limit());
+            long timestamp = dis.readLong();
+            ByteBuffer value = FBUtilities.readByteArray(dis);
+            return new CounterColumn(name, value, timestamp, partitionedCounter, timestampOfLastDelete);
+        }
+        else if ((b & EXPIRATION_MASK) != 0)
         {
             int ttl = dis.readInt();
             int expiration = dis.readInt();

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/CompactionManager.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/CompactionManager.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/CompactionManager.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/CompactionManager.java Tue Dec 21 22:17:09 2010
@@ -52,6 +52,7 @@ import org.apache.cassandra.io.sstable.*
 import org.apache.cassandra.io.util.FileUtils;
 import org.apache.cassandra.service.AntiEntropyService;
 import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.streaming.OperationType;
 import org.apache.cassandra.utils.FBUtilities;
 import org.apache.cassandra.utils.Pair;
 import org.cliffc.high_scale_lib.NonBlockingHashMap;
@@ -595,11 +596,11 @@ public class CompactionManager implement
         else
             return executor.submit(runnable);
     }
-    
-    public Future<SSTableReader> submitSSTableBuild(Descriptor desc)
+
+    public Future<SSTableReader> submitSSTableBuild(Descriptor desc, OperationType type)
     {
         // invalid descriptions due to missing or dropped CFS are handled by SSTW and StreamInSession.
-        final SSTableWriter.Builder builder = SSTableWriter.createBuilder(desc);
+        final SSTableWriter.Builder builder = SSTableWriter.createBuilder(desc, type);
         Callable<SSTableReader> callable = new Callable<SSTableReader>()
         {
             public SSTableReader call() throws IOException

Added: cassandra/trunk/src/java/org/apache/cassandra/db/CounterColumn.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/CounterColumn.java?rev=1051679&view=auto
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/CounterColumn.java (added)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/CounterColumn.java Tue Dec 21 22:17:09 2010
@@ -0,0 +1,287 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.nio.ByteBuffer;
+import java.security.MessageDigest;
+import java.util.Arrays;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cassandra.db.context.CounterContext;
+import org.apache.cassandra.db.context.IContext.ContextRelationship;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.FBUtilities;
+
+/**
+ * A column that represents a partitioned counter.
+ */
+public class CounterColumn extends Column
+{
+    private static Logger logger = Logger.getLogger(CounterColumn.class);
+
+    private static CounterContext contextManager = CounterContext.instance();
+
+    protected ByteBuffer value;                 // NOT final: delta OR total of partitioned counter
+    protected byte[] partitionedCounter;        // NOT final: only modify inline, carefully
+    protected final long timestampOfLastDelete;
+
+    public CounterColumn(ByteBuffer name, ByteBuffer value, long timestamp)
+    {
+      this(name, value, timestamp, contextManager.create());
+    }
+
+    public CounterColumn(ByteBuffer name, ByteBuffer value, long timestamp, byte[] partitionedCounter)
+    {
+      this(name, value, timestamp, partitionedCounter, Long.MIN_VALUE);
+    }
+
+    public CounterColumn(ByteBuffer name, ByteBuffer value, long timestamp, byte[] partitionedCounter, long timestampOfLastDelete)
+    {
+        super(name, FBUtilities.EMPTY_BYTE_BUFFER, timestamp);
+        this.value = value;
+        this.partitionedCounter = partitionedCounter;
+        this.timestampOfLastDelete = timestampOfLastDelete;
+    }
+
+    @Override
+    public ByteBuffer value()
+    {
+        return value;
+    }
+
+    public byte[] partitionedCounter()
+    {
+        return partitionedCounter;
+    }
+
+    public long timestampOfLastDelete()
+    {
+        return timestampOfLastDelete;
+    }
+
+    @Override
+    public int size()
+    {
+        /*
+         * An expired column adds to a Column : 
+         *    4 bytes for length of partitionedCounter
+         *  + length of partitionedCounter
+         *  + 8 bytes for timestampOfLastDelete
+         */
+        return super.size() + DBConstants.intSize_ + partitionedCounter.length + DBConstants.tsSize_;
+    }
+
+    @Override
+    public IColumn diff(IColumn column)
+    {
+        assert column instanceof CounterColumn : "Wrong class type.";
+
+        if (timestamp() < column.timestamp())
+            return column;
+        if (timestampOfLastDelete() < ((CounterColumn)column).timestampOfLastDelete())
+            return column;
+        ContextRelationship rel = contextManager.diff(
+            ((CounterColumn)column).partitionedCounter(),
+            partitionedCounter());
+        if (ContextRelationship.GREATER_THAN == rel || ContextRelationship.DISJOINT == rel)
+            return column;
+        return null;
+    }
+
+    @Override
+    public void updateDigest(MessageDigest digest)
+    {
+        digest.update(name.array(),name.position()+name.arrayOffset(),name.remaining());
+        digest.update(value.array(),value.position()+name.arrayOffset(),value.remaining());
+        digest.update(FBUtilities.toByteArray(timestamp));
+        digest.update(partitionedCounter);
+        digest.update(FBUtilities.toByteArray(timestampOfLastDelete));
+    }
+
+    @Override
+    public IColumn reconcile(IColumn column)
+    {
+        assert (column instanceof CounterColumn) || (column instanceof DeletedColumn) : "Wrong class type.";
+
+        if (isMarkedForDelete())
+        {
+            if (column.isMarkedForDelete()) // tombstone + tombstone: keep later tombstone
+            {
+                return timestamp() > column.timestamp() ? this : column;
+            }
+            else // tombstone + live: track last tombstone
+            {
+                if (timestamp() > column.timestamp()) // tombstone > live
+                {
+                    return this;
+                }
+                // tombstone <= live last delete
+                if (timestamp() <= ((CounterColumn)column).timestampOfLastDelete())
+                {
+                    return column;
+                }
+                // tombstone > live last delete
+                return new CounterColumn(
+                    column.name(),
+                    column.value(),
+                    column.timestamp(),
+                    ((CounterColumn)column).partitionedCounter(),
+                    timestamp());
+            }
+        }
+        else if (column.isMarkedForDelete()) // live + tombstone: track last tombstone
+        {
+            if (timestamp() < column.timestamp()) // live < tombstone
+            {
+                return column;
+            }
+            // live last delete >= tombstone
+            if (timestampOfLastDelete() >= column.timestamp())
+            {
+                return this;
+            }
+            // live last delete < tombstone
+            return new CounterColumn(
+                name(),
+                value(),
+                timestamp(),
+                partitionedCounter(),
+                column.timestamp());
+        }
+        // live + live: merge clocks; update value
+        byte[] mergedPartitionedCounter = contextManager.merge(
+            partitionedCounter(),
+            ((CounterColumn)column).partitionedCounter());
+		ByteBuffer byteBufferValue;
+		if (0 == mergedPartitionedCounter.length)
+		{
+			long mergedValue = value().getLong(value().arrayOffset()) +
+                               column.value().getLong(column.value().arrayOffset());
+			byteBufferValue = FBUtilities.toByteBuffer(mergedValue);
+		} else
+			byteBufferValue = ByteBuffer.wrap(contextManager.total(mergedPartitionedCounter));
+        return new CounterColumn(
+            name(),
+			byteBufferValue,
+            Math.max(timestamp(), column.timestamp()),
+            mergedPartitionedCounter,
+            Math.max(timestampOfLastDelete(), ((CounterColumn)column).timestampOfLastDelete()));
+    }
+
+    @Override
+    public boolean equals(Object o)
+    {
+        if (this == o)
+            return true;
+        if (o == null || getClass() != o.getClass())
+            return false;
+
+        CounterColumn column = (CounterColumn)o;
+
+        if (timestamp != column.timestamp)
+            return false;
+
+        if (timestampOfLastDelete != column.timestampOfLastDelete)
+            return false;
+
+        if (!Arrays.equals(partitionedCounter, column.partitionedCounter))
+            return false;
+
+        if (!name.equals(column.name))
+            return false;
+
+        return value.equals(column.value);
+    }
+
+    @Override
+    public int hashCode()
+    {
+        int result = super.hashCode();
+        result = 31 * result + (partitionedCounter != null ? Arrays.hashCode(partitionedCounter) : 0);
+        result = 31 * result + (int)(timestampOfLastDelete ^ (timestampOfLastDelete >>> 32));
+        return result;
+    }
+
+    @Override
+    public IColumn deepCopy()
+    {
+        return new CounterColumn(
+            ByteBufferUtil.clone(name),
+            ByteBufferUtil.clone(value),
+            timestamp,
+            partitionedCounter,
+            timestampOfLastDelete);
+    }
+
+    @Override
+    public String getString(AbstractType comparator)
+    {
+        StringBuilder sb = new StringBuilder();
+        sb.append(comparator.getString(name));
+        sb.append(":");
+        sb.append(isMarkedForDelete());
+        sb.append(":");
+        sb.append(value.getLong(value.arrayOffset()));
+        sb.append("@");
+        sb.append(timestamp());
+        sb.append("!");
+        sb.append(timestampOfLastDelete);
+        sb.append("@");
+        sb.append(contextManager.toString(partitionedCounter));
+        return sb.toString();
+    }
+
+    private void updateValue()
+    {
+        value = ByteBuffer.wrap(contextManager.total(partitionedCounter));
+    }
+
+    public void update(InetAddress node)
+    {
+        long delta = value.getLong(value.arrayOffset());
+        partitionedCounter = contextManager.update(partitionedCounter, node, delta);
+        updateValue();
+    }
+
+    public CounterColumn cleanNodeCounts(InetAddress node)
+    {
+        //XXX: inline modification non-destructive; cases:
+        //     1) AES post-stream
+        //     2) RRR, after CF.cloneMe()
+        //     3) RRR, after CF.diff() which creates a new CF
+        byte[] cleanPartitionedCounter  = contextManager.cleanNodeCounts(partitionedCounter, node);
+        if (cleanPartitionedCounter == partitionedCounter)
+            return this;
+        if (0 == cleanPartitionedCounter.length)
+            return null;
+        return new CounterColumn(
+            name,
+            ByteBuffer.wrap(contextManager.total(cleanPartitionedCounter)),
+            timestamp,
+            cleanPartitionedCounter,
+            timestampOfLastDelete
+            );
+    }
+}
+

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/DeletedColumn.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/DeletedColumn.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/DeletedColumn.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/DeletedColumn.java Tue Dec 21 22:17:09 2010
@@ -56,6 +56,14 @@ public class DeletedColumn extends Colum
     {
        return value.getInt(value.position()+value.arrayOffset()	);
     }
+
+    @Override
+    public IColumn reconcile(IColumn column)
+    {
+        if (column instanceof DeletedColumn)
+            return super.reconcile(column);
+        return column.reconcile(this);
+    }
     
     @Override
     public IColumn deepCopy()

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/IColumnContainer.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/IColumnContainer.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/IColumnContainer.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/IColumnContainer.java Tue Dec 21 22:17:09 2010
@@ -20,15 +20,20 @@ package org.apache.cassandra.db;
  * 
  */
 
+import java.nio.ByteBuffer;
+import java.util.Collection;
 
 import org.apache.cassandra.db.marshal.AbstractType;
 
 public interface IColumnContainer
 {
     public void addColumn(IColumn column);
+    public void remove(ByteBuffer columnName);
 
     public boolean isMarkedForDelete();
     public long getMarkedForDeleteAt();
 
     public AbstractType getComparator();
+
+    public Collection<IColumn> getSortedColumns();
 }

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/Memtable.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/Memtable.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/Memtable.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/Memtable.java Tue Dec 21 22:17:09 2010
@@ -171,8 +171,18 @@ public class Memtable implements Compara
         {
             public void runMayThrow() throws IOException
             {
-                cfs.addSSTable(writeSortedContents());
-                cfs.getMemtablesPendingFlush().remove(Memtable.this);
+                if (!cfs.reverseReadWriteOrder())
+                {
+                    //XXX: race condition: may allow double reconcile; but never misses an MT
+                    cfs.addSSTable(writeSortedContents());
+                    cfs.getMemtablesPendingFlush().remove(Memtable.this);
+                }
+                else
+                {
+                    //XXX: race condition: may miss an MT, but no double counts
+                    cfs.getMemtablesPendingFlush().remove(Memtable.this);
+                    cfs.addSSTable(writeSortedContents());
+                }
                 latch.countDown();
             }
         });

Added: cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteTask.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteTask.java?rev=1051679&view=auto
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteTask.java (added)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteTask.java Tue Dec 21 22:17:09 2010
@@ -0,0 +1,129 @@
+package org.apache.cassandra.db;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.net.InetAddress;
+import java.nio.ByteBuffer;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cassandra.db.filter.QueryPath;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.AbstractCommutativeType;
+import org.apache.cassandra.net.Message;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.utils.FBUtilities;
+
+public class ReplicateOnWriteTask implements Runnable
+{
+    private RowMutation mutation;
+    private static Logger logger = Logger.getLogger(ReplicateOnWriteTask.class);
+
+    public ReplicateOnWriteTask(RowMutation mutation)
+    {
+        this.mutation = mutation;
+    }
+
+    public void run()
+    {
+        // construct SliceByNamesReadCommand for CFs to repair
+        List<ReadCommand> readCommands = new LinkedList<ReadCommand>();
+        for (ColumnFamily columnFamily : mutation.getColumnFamilies())
+        {
+            // filter out non-repair CFs
+            if (!columnFamily.metadata().getReplicateOnWrite())
+                continue;
+
+            // CF type: regular
+            if (!columnFamily.isSuper())
+            {
+                QueryPath queryPath = new QueryPath(columnFamily.metadata().cfName);
+                ReadCommand readCommand = new SliceByNamesReadCommand(
+                    mutation.getTable(),
+                    mutation.key(),
+                    queryPath,
+                    columnFamily.getColumnNames()
+                    );
+
+                readCommands.add(readCommand);
+                continue;
+            }
+
+            // CF type: super
+            for (IColumn superColumn : columnFamily.getSortedColumns())
+            {
+                QueryPath queryPath = new QueryPath(columnFamily.metadata().cfName, superColumn.name());
+
+                // construct set of sub-column names
+                Collection<IColumn> subColumns = superColumn.getSubColumns();
+                Collection<ByteBuffer> subColNames = new HashSet<ByteBuffer>(subColumns.size());
+                for (IColumn subCol : subColumns)
+                {
+                    subColNames.add(subCol.name());
+                }
+
+                ReadCommand readCommand = new SliceByNamesReadCommand(
+                    mutation.getTable(),
+                    mutation.key(),
+                    queryPath,
+                    subColNames
+                    );
+                readCommands.add(readCommand);
+            }
+        }
+
+        if (0 == readCommands.size())
+            return;
+
+        try
+        {
+            // send repair to non-local replicas
+            List<InetAddress> foreignReplicas = StorageService.instance.getLiveNaturalEndpoints(
+                mutation.getTable(),
+                mutation.key()
+                );
+            foreignReplicas.remove(FBUtilities.getLocalAddress()); // remove local replica
+
+            // create a repair RowMutation
+            RowMutation repairRowMutation = new RowMutation(mutation.getTable(), mutation.key());
+            for (ReadCommand readCommand : readCommands)
+            {
+                Table table = Table.open(readCommand.table);
+                Row row = readCommand.getRow(table);
+                AbstractType defaultValidator = row.cf.metadata().getDefaultValidator();
+                if (defaultValidator.isCommutative())
+                {
+                    /**
+                     * Clean out contexts for all nodes we're sending the repair to, otherwise,
+                     * we could send a context which is local to one of the foreign replicas,
+                     * which would then incorrectly add that to its own count, because
+                     * local resolution aggregates.
+                     */
+                    // note: the following logic could be optimized
+                    for (InetAddress foreignNode : foreignReplicas)
+                    {
+                        ((AbstractCommutativeType)defaultValidator).cleanContext(row.cf, foreignNode);
+                    }
+                }
+                repairRowMutation.add(row.cf);
+            }
+
+            // send repair to non-local replicas
+            for (InetAddress foreignReplica : foreignReplicas)
+            {
+                RowMutationMessage repairMessage = new RowMutationMessage(
+                    repairRowMutation);
+                Message message = repairMessage.makeRowMutationMessage(StorageService.Verb.REPLICATE_ON_WRITE);
+                MessagingService.instance.sendOneWay(message, foreignReplica);
+            }
+        }
+        catch (IOException e)
+        {
+            throw new RuntimeException(e);
+        }
+    }
+}

Added: cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteVerbHandler.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteVerbHandler.java?rev=1051679&view=auto
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteVerbHandler.java (added)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/ReplicateOnWriteVerbHandler.java Tue Dec 21 22:17:09 2010
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db;
+
+import java.io.*;
+
+import org.apache.cassandra.net.IVerbHandler;
+import org.apache.cassandra.net.Message;
+import org.apache.cassandra.utils.FBUtilities;
+
+import org.apache.log4j.Logger;
+
+public class ReplicateOnWriteVerbHandler implements IVerbHandler
+{
+    private static Logger logger = Logger.getLogger(ReplicateOnWriteVerbHandler.class);
+
+    public void doVerb(Message message)
+    {
+        byte[] body = message.getMessageBody();
+        ByteArrayInputStream buffer = new ByteArrayInputStream(body);
+
+        try
+        {
+            RowMutationMessage rmMsg = RowMutationMessage.serializer().deserialize(new DataInputStream(buffer));
+            RowMutation rm = rmMsg.getRowMutation();
+            if (logger.isDebugEnabled())
+                logger.debug("repair-on-write for key " + FBUtilities.bytesToHex(rm.key()));
+            rm.apply();
+        }
+        catch (IOException e)
+        {
+            throw new IOError(e);
+        }
+    }
+}

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/RowMutation.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/RowMutation.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/RowMutation.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/RowMutation.java Tue Dec 21 22:17:09 2010
@@ -23,6 +23,9 @@ import java.io.ByteArrayOutputStream;
 import java.io.DataInputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.*;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -43,6 +46,9 @@ import org.apache.cassandra.thrift.Delet
 import org.apache.cassandra.thrift.Mutation;
 import org.apache.cassandra.utils.ByteBufferUtil;
 import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.AbstractCommutativeType;
+import org.apache.commons.lang.ArrayUtils;
 import org.apache.commons.lang.StringUtils;
 
 public class RowMutation
@@ -316,7 +322,21 @@ public class RowMutation
             rm.delete(new QueryPath(cfName, del.super_column), del.timestamp);
         }
     }
-    
+
+    /**
+     * Update the context of all CounterColumns in this RowMutation
+     */
+    public void updateCommutativeTypes(InetAddress node)
+    {
+        for (ColumnFamily cf : modifications_.values())
+        {
+            AbstractType defaultValidator = cf.metadata().getDefaultValidator();
+            if (!defaultValidator.isCommutative())
+                continue;
+            ((AbstractCommutativeType)defaultValidator).update(cf, node);
+        }
+    }
+
     static RowMutation fromBytes(byte[] raw) throws IOException
     {
         RowMutation rm = serializer_.deserialize(new DataInputStream(new ByteArrayInputStream(raw)));

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/RowMutationVerbHandler.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/RowMutationVerbHandler.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/RowMutationVerbHandler.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/RowMutationVerbHandler.java Tue Dec 21 22:17:09 2010
@@ -31,6 +31,8 @@ import org.apache.cassandra.net.Message;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import org.apache.cassandra.concurrent.Stage;
+import org.apache.cassandra.concurrent.StageManager;
 import org.apache.cassandra.net.*;
 import org.apache.cassandra.utils.ByteBufferUtil;
 import org.apache.cassandra.utils.FBUtilities;
@@ -74,6 +76,10 @@ public class RowMutationVerbHandler impl
             if (logger_.isDebugEnabled())
               logger_.debug(rm + " applied.  Sending response to " + message.getMessageId() + "@" + message.getFrom());
             MessagingService.instance.sendOneWay(responseMessage, message.getFrom());
+
+            // repair-on-write (remote message)
+            ReplicateOnWriteTask replicateOnWriteTask = new ReplicateOnWriteTask(rm);
+            StageManager.getStage(Stage.REPLICATE_ON_WRITE).execute(replicateOnWriteTask);
         }
         catch (IOException e)
         {

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/SuperColumn.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/SuperColumn.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/SuperColumn.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/SuperColumn.java Tue Dec 21 22:17:09 2010
@@ -99,6 +99,11 @@ public class SuperColumn implements ICol
     	return columns_.values();
     }
 
+    public Collection<IColumn> getSortedColumns()
+    {
+        return getSubColumns();
+    }
+
     public IColumn getSubColumn(ByteBuffer columnName)
     {
         IColumn column = columns_.get(columnName);

Added: cassandra/trunk/src/java/org/apache/cassandra/db/context/CounterContext.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/context/CounterContext.java?rev=1051679&view=auto
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/context/CounterContext.java (added)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/context/CounterContext.java Tue Dec 21 22:17:09 2010
@@ -0,0 +1,553 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.context;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cassandra.db.DBConstants;
+import org.apache.cassandra.db.context.IContext;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.commons.lang.ArrayUtils;
+
+/**
+ * An implementation of a partitioned counter context.
+ *
+ * The data structure is:
+ *   a vector of (node id, logical clock, count) tuples.
+ *
+ * On update, the node will:
+ *   1) increment the logical clock, and
+ *   2) update the count associated w/ its tuple.
+ *
+ * The logical clock represents the # of operations executed
+ * by the node.  The aggregated count can be determined
+ * by rolling up all the counts from each tuple.
+ *
+ * NOTE: only a given node id may increment its associated count and
+ * care must be taken to ensure that tuples are correctly made consistent.
+ */
+public class CounterContext implements IContext
+{
+    private static final int idLength;
+    private static final FBUtilities.ByteArrayWrapper idWrapper;
+    private static final int clockLength = DBConstants.longSize_;
+    private static final int countLength = DBConstants.longSize_;
+    private static final int stepLength; // length: id + logical clock + count
+
+    // lazy-load singleton
+    private static class LazyHolder
+    {
+        private static final CounterContext counterContext = new CounterContext();
+    }
+
+    static
+    {
+        byte[] id  = FBUtilities.getLocalAddress().getAddress();
+        idLength   = id.length;
+        idWrapper  = new FBUtilities.ByteArrayWrapper(id);
+        stepLength = idLength + clockLength + countLength;
+    }
+
+    public static CounterContext instance()
+    {
+        return LazyHolder.counterContext;
+    }
+
+    /**
+     * Creates an initial counter context.
+     *
+     * @return an empty counter context.
+     */
+    public byte[] create()
+    {
+        return new byte[0];
+    }
+    
+    // write a tuple (node id, clock, count) at the front
+    protected static void writeElement(byte[] context, byte[] id, long clock, long count)
+    {
+        writeElementAtStepOffset(context, 0, id, clock, count);
+    }
+
+    // write a tuple (node id, clock, count) at step offset
+    protected static void writeElementAtStepOffset(byte[] context, int stepOffset, byte[] id, long clock, long count)
+    {
+        int offset = stepOffset * stepLength;
+        System.arraycopy(id, 0, context, offset, idLength);
+        FBUtilities.copyIntoBytes(context, offset + idLength, clock);
+        FBUtilities.copyIntoBytes(context, offset + idLength + clockLength, count);
+    }
+
+    public byte[] update(byte[] context, InetAddress node, long delta)
+    {
+        // calculate node id
+        byte[] nodeId = node.getAddress();
+
+        // look for this node id
+        for (int offset = 0; offset < context.length; offset += stepLength)
+        {
+            if (FBUtilities.compareByteSubArrays(nodeId, 0, context, offset, idLength) != 0)
+                continue;
+
+            // node id found: increment clock, update count; shift to front
+            long clock = FBUtilities.byteArrayToLong(context, offset + idLength);
+            long count = FBUtilities.byteArrayToLong(context, offset + idLength + clockLength);
+
+            System.arraycopy(
+                context,
+                0,
+                context,
+                stepLength,
+                offset);
+            writeElement(context, nodeId, clock + 1L, count + delta);
+
+            return context;
+        }
+
+        // node id not found: widen context
+        byte[] previous = context;
+        context = new byte[previous.length + stepLength];
+
+        writeElement(context, nodeId, 1L, delta);
+        System.arraycopy(
+            previous,
+            0,
+            context,
+            stepLength,
+            previous.length);
+
+        return context;
+    }
+
+    // swap bytes of step length in context
+    protected static void swapElement(byte[] context, int left, int right)
+    {
+        if (left == right) return;
+
+        byte temp;
+        for (int i = 0; i < stepLength; i++)
+        {
+            temp = context[left+i];
+            context[left+i] = context[right+i];
+            context[right+i] = temp;
+        }
+    }
+
+    // partition bytes of step length in context (for quicksort)
+    protected static int partitionElements(byte[] context, int left, int right, int pivotIndex)
+    {
+        int leftOffset  = left       * stepLength;
+        int rightOffset = right      * stepLength;
+        int pivotOffset = pivotIndex * stepLength;
+
+        byte[] pivotValue = ArrayUtils.subarray(context, pivotOffset, pivotOffset + stepLength);
+        swapElement(context, pivotOffset, rightOffset);
+        int storeOffset = leftOffset;
+        for (int i = leftOffset; i < rightOffset; i += stepLength)
+        {
+            if (FBUtilities.compareByteSubArrays(context, i, pivotValue, 0, stepLength) <= 0)
+            {
+                swapElement(context, i, storeOffset);
+                storeOffset += stepLength;
+            }
+        }
+        swapElement(context, storeOffset, rightOffset);
+        return storeOffset / stepLength;
+    }
+
+    // quicksort helper
+    protected static void sortElementsByIdHelper(byte[] context, int left, int right)
+    {
+        if (right <= left) return;
+
+        int pivotIndex = (left + right) / 2;
+        int pivotIndexNew = partitionElements(context, left, right, pivotIndex);
+        sortElementsByIdHelper(context, left, pivotIndexNew - 1);
+        sortElementsByIdHelper(context, pivotIndexNew + 1, right);
+    }
+
+    // quicksort context by id
+    protected static byte[] sortElementsById(byte[] context)
+    {
+        assert 0 == (context.length % stepLength) : "context size is not correct.";
+        sortElementsByIdHelper(
+            context,
+            0,
+            (int)(context.length / stepLength) - 1);
+        return context;
+    }
+
+    /**
+     * Determine the count relationship between two contexts.
+     *
+     * EQUAL:        Equal set of nodes and every count is equal.
+     * GREATER_THAN: Superset of nodes and every count is equal or greater than its corollary.
+     * LESS_THAN:    Subset of nodes and every count is equal or less than its corollary.
+     * DISJOINT:     Node sets are not equal and/or counts are not all greater or less than.
+     *
+     * Strategy:
+     *   compare node logical clocks (like a version vector).
+     *
+     * @param left
+     *            counter context.
+     * @param right
+     *            counter context.
+     * @return the ContextRelationship between the contexts.
+     */
+    public ContextRelationship diff(byte[] left, byte[] right)
+    {
+        left  = sortElementsById(left);
+        right = sortElementsById(right);
+
+        ContextRelationship relationship = ContextRelationship.EQUAL;
+
+        int leftIndex  = 0;
+        int rightIndex = 0;
+        while (leftIndex < left.length && rightIndex < right.length)
+        {
+            // compare id bytes
+            int compareId = FBUtilities.compareByteSubArrays(left, leftIndex, right, rightIndex, idLength);
+            if (compareId == 0)
+            {
+                long leftClock  = FBUtilities.byteArrayToLong(left,  leftIndex + idLength);
+                long rightClock = FBUtilities.byteArrayToLong(right, rightIndex + idLength);
+
+                // advance indexes
+                leftIndex  += stepLength;
+                rightIndex += stepLength;
+
+                // process clock comparisons
+                if (leftClock == rightClock)
+                {
+                    continue;
+                }
+                else if (leftClock > rightClock)
+                {
+                    if (relationship == ContextRelationship.EQUAL)
+                    {
+                        relationship = ContextRelationship.GREATER_THAN;
+                    }
+                    else if (relationship == ContextRelationship.GREATER_THAN)
+                    {
+                        continue;
+                    }
+                    else
+                    {
+                        // relationship == ContextRelationship.LESS_THAN
+                        return ContextRelationship.DISJOINT;
+                    }
+                }
+                else
+                // leftClock < rightClock
+                {
+                    if (relationship == ContextRelationship.EQUAL)
+                    {
+                        relationship = ContextRelationship.LESS_THAN;
+                    }
+                    else if (relationship == ContextRelationship.GREATER_THAN)
+                    {
+                        return ContextRelationship.DISJOINT;
+                    }
+                    else
+                    {
+                        // relationship == ContextRelationship.LESS_THAN
+                        continue;
+                    }
+                }
+            }
+            else if (compareId > 0)
+            {
+                // only advance the right context
+                rightIndex += stepLength;
+
+                if (relationship == ContextRelationship.EQUAL)
+                {
+                    relationship = ContextRelationship.LESS_THAN;
+                }
+                else if (relationship == ContextRelationship.GREATER_THAN)
+                {
+                    return ContextRelationship.DISJOINT;
+                }
+                else
+                {
+                    // relationship == ContextRelationship.LESS_THAN
+                    continue;
+                }
+            }
+            else
+            {
+                // compareId < 0
+                // only advance the left context
+                leftIndex += stepLength;
+
+                if (relationship == ContextRelationship.EQUAL)
+                {
+                    relationship = ContextRelationship.GREATER_THAN;
+                }
+                else if (relationship == ContextRelationship.GREATER_THAN)
+                {
+                    continue;
+                }
+                else
+                // relationship == ContextRelationship.LESS_THAN
+                {
+                    return ContextRelationship.DISJOINT;
+                }
+            }
+        }
+
+        // check final lengths
+        if (leftIndex < left.length)
+        {
+            if (relationship == ContextRelationship.EQUAL)
+            {
+                return ContextRelationship.GREATER_THAN;
+            }
+            else if (relationship == ContextRelationship.LESS_THAN)
+            {
+                return ContextRelationship.DISJOINT;
+            }
+        }
+        else if (rightIndex < right.length)
+        {
+            if (relationship == ContextRelationship.EQUAL)
+            {
+                return ContextRelationship.LESS_THAN;
+            }
+            else if (relationship == ContextRelationship.GREATER_THAN)
+            {
+                return ContextRelationship.DISJOINT;
+            }
+        }
+
+        return relationship;
+    }
+
+    private class CounterNode
+    {
+        public final long clock;
+        public final long count;
+
+        public CounterNode(long clock, long count)
+        {
+            this.clock = clock;
+            this.count = count;
+        }
+
+        public int compareClockTo(CounterNode o)
+        {
+            if (clock == o.clock)
+            {
+                return 0;
+            }
+            else if (clock > o.clock)
+            {
+                return 1;
+            }
+            // clock < o.clock
+            return -1;
+        }
+
+        @Override
+        public String toString()
+        {
+            return "(" + clock + "," + count + ")";
+        }
+    }
+
+    /**
+     * Return a context w/ an aggregated count for each node id.
+     *
+     * @param left
+     *            counter context.
+     * @param right
+     *            counter context.
+     */
+    public byte[] merge(byte[] left, byte[] right)
+    {
+        // strategy:
+        //   1) map id -> (clock, count)
+        //      a) local id:  sum clocks, counts
+        //      b) remote id: keep highest clock, count (reconcile)
+        //   2) create a context from sorted array
+        Map<FBUtilities.ByteArrayWrapper, CounterNode> contextsMap =
+            new HashMap<FBUtilities.ByteArrayWrapper, CounterNode>();
+
+        // map left context: id -> (clock, count)
+        for (int offset = 0; offset < left.length; offset += stepLength)
+        {
+            FBUtilities.ByteArrayWrapper id = new FBUtilities.ByteArrayWrapper(
+                ArrayUtils.subarray(left, offset, offset + idLength));
+            long clock = FBUtilities.byteArrayToLong(left, offset + idLength);
+            long count = FBUtilities.byteArrayToLong(left, offset + idLength + clockLength);
+
+            contextsMap.put(id, new CounterNode(clock, count));
+        }
+
+        // map right context: id -> (clock, count)
+        for (int offset = 0; offset < right.length; offset += stepLength)
+        {
+            FBUtilities.ByteArrayWrapper id = new FBUtilities.ByteArrayWrapper(
+                ArrayUtils.subarray(right, offset, offset + idLength));
+            long clock = FBUtilities.byteArrayToLong(right, offset + idLength);
+            long count = FBUtilities.byteArrayToLong(right, offset + idLength + clockLength);
+
+            if (!contextsMap.containsKey(id))
+            {
+                contextsMap.put(id, new CounterNode(clock, count));
+                continue;
+            }
+
+            CounterNode node = contextsMap.get(id);
+
+            // local id: sum clocks, counts
+            if (this.idWrapper.equals(id))
+            {
+                contextsMap.put(id, new CounterNode(
+                    clock + node.clock,
+                    count + node.count));
+                continue;
+            }
+
+            // remote id: keep highest clock and its count
+            if (node.clock < clock)
+            {
+                contextsMap.put(id, new CounterNode(clock, count));
+            }
+        }
+
+        // sort merged tuples
+        List<Map.Entry<FBUtilities.ByteArrayWrapper, CounterNode>> contextsList =
+            new ArrayList<Map.Entry<FBUtilities.ByteArrayWrapper, CounterNode>>(
+                    contextsMap.entrySet());
+        Collections.sort(
+            contextsList,
+            new Comparator<Map.Entry<FBUtilities.ByteArrayWrapper, CounterNode>>()
+            {
+                public int compare(
+                    Map.Entry<FBUtilities.ByteArrayWrapper, CounterNode> e1,
+                    Map.Entry<FBUtilities.ByteArrayWrapper, CounterNode> e2)
+                {
+                    // reversed
+                    return e2.getValue().compareClockTo(e1.getValue());
+                }
+            });
+
+        // create merged context
+        int length = contextsList.size();
+        byte[] merged = new byte[length * stepLength];
+        for (int i = 0; i < length; i++)
+        {
+            Map.Entry<FBUtilities.ByteArrayWrapper, CounterNode> entry = contextsList.get(i);
+            writeElementAtStepOffset(
+                merged,
+                i,
+                entry.getKey().data,
+                entry.getValue().clock,
+                entry.getValue().count);
+        }
+        return merged;
+    }
+
+    /**
+     * Human-readable String from context.
+     *
+     * @param context
+     *            version context.
+     * @return a human-readable String of the context.
+     */
+    public String toString(byte[] context)
+    {
+        StringBuilder sb = new StringBuilder();
+        sb.append("[");
+        for (int offset = 0; offset < context.length; offset += stepLength)
+        {
+            if (offset > 0)
+            {
+                sb.append(",");
+            }
+            sb.append("{");
+            try
+            {
+                InetAddress address = InetAddress.getByAddress(
+                            ArrayUtils.subarray(context, offset, offset + idLength));
+                sb.append(address.getHostAddress());
+            }
+            catch (UnknownHostException uhe)
+            {
+                sb.append("?.?.?.?");
+            }
+            sb.append(", ");
+            sb.append(FBUtilities.byteArrayToLong(context, offset + idLength));
+            sb.append(", ");
+            sb.append(FBUtilities.byteArrayToLong(context, offset + idLength + clockLength));
+
+            sb.append("}");
+        }
+        sb.append("]");
+        return sb.toString();
+    }
+
+    // return an aggregated count across all node ids
+    public byte[] total(byte[] context)
+    {
+        long total = 0L;
+
+        for (int offset = 0; offset < context.length; offset += stepLength)
+        {
+            long count = FBUtilities.byteArrayToLong(context, offset + idLength + clockLength);
+            total += count;
+        }
+
+        return FBUtilities.toByteArray(total);
+    }
+
+    // remove the count for a given node id
+    public byte[] cleanNodeCounts(byte[] context, InetAddress node)
+    {
+        // calculate node id
+        byte[] nodeId = node.getAddress();
+
+        // look for this node id
+        for (int offset = 0; offset < context.length; offset += stepLength)
+        {
+            if (FBUtilities.compareByteSubArrays(context, offset, nodeId, 0, idLength) != 0)
+                continue;
+
+            // node id found: remove node count
+            byte[] truncatedContext = new byte[context.length - stepLength];
+            System.arraycopy(context, 0, truncatedContext, 0, offset);
+            System.arraycopy(
+                context,
+                offset + stepLength,
+                truncatedContext,
+                offset,
+                context.length - (offset + stepLength));
+            return truncatedContext;
+        }
+
+        return context;
+    }
+}

Added: cassandra/trunk/src/java/org/apache/cassandra/db/context/IContext.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/context/IContext.java?rev=1051679&view=auto
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/context/IContext.java (added)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/context/IContext.java Tue Dec 21 22:17:09 2010
@@ -0,0 +1,79 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.context;
+
+import java.net.InetAddress;
+import java.util.List;
+
+/**
+ * An opaque commutative context.
+ *
+ * Maintains a byte[] context that represents a partitioned commutative value.
+ */
+public interface IContext
+{
+    public static enum ContextRelationship
+    {
+        EQUAL,
+        GREATER_THAN,
+        LESS_THAN,
+        DISJOINT
+    };
+
+    /**
+     * Creates an initial context.
+     *
+     * @return the initial context.
+     */
+    public byte[] create();
+
+    /**
+     * Determine the relationship between two contexts.
+     *
+     * EQUAL:        Equal set of nodes and every count is equal.
+     * GREATER_THAN: Superset of nodes and every count is equal or greater than its corollary.
+     * LESS_THAN:    Subset of nodes and every count is equal or less than its corollary.
+     * DISJOINT:     Node sets are not equal and/or counts are not all greater or less than.
+     *
+     * @param left
+     *            context.
+     * @param right
+     *            context.
+     * @return the ContextRelationship between the contexts.
+     */
+    public ContextRelationship diff(byte[] left, byte[] right);
+
+    /**
+     * Return a context w/ an aggregated count for each node id.
+     *
+     * @param left
+     *            context.
+     * @param right
+     *            context.
+     */
+    public byte[] merge(byte[] left, byte[] right);
+
+    /**
+     * Human-readable String from context.
+     *
+     * @param context
+     *            context.
+     * @return a human-readable String of the context.
+     */
+    public String toString(byte[] context);
+}

Added: cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractCommutativeType.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractCommutativeType.java?rev=1051679&view=auto
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractCommutativeType.java (added)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractCommutativeType.java Tue Dec 21 22:17:09 2010
@@ -0,0 +1,50 @@
+/*
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * 
+ */
+package org.apache.cassandra.db.marshal;
+
+import java.net.InetAddress;
+import java.nio.ByteBuffer;
+
+import org.apache.cassandra.db.Column;
+import org.apache.cassandra.db.IColumnContainer;
+
+public abstract class AbstractCommutativeType extends AbstractType
+{
+    public boolean isCommutative()
+    {
+        return true;
+    }
+
+    /**
+     * create commutative column
+     */
+    public abstract Column createColumn(ByteBuffer name, ByteBuffer value, long timestamp);
+
+    /**
+     * update commutative columns for target node
+     */
+    public abstract void update(IColumnContainer cc, InetAddress node);
+
+    /**
+     * remove target node from commutative columns
+     */
+    public abstract void cleanContext(IColumnContainer cc, InetAddress node);
+}

Modified: cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java Tue Dec 21 22:17:09 2010
@@ -91,4 +91,9 @@ public abstract class AbstractType imple
         }
         return builder.toString();
     }
+
+    public boolean isCommutative()
+    {
+        return false;
+    }
 }

Added: cassandra/trunk/src/java/org/apache/cassandra/db/marshal/CounterColumnType.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/db/marshal/CounterColumnType.java?rev=1051679&view=auto
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/db/marshal/CounterColumnType.java (added)
+++ cassandra/trunk/src/java/org/apache/cassandra/db/marshal/CounterColumnType.java Tue Dec 21 22:17:09 2010
@@ -0,0 +1,133 @@
+/*
+ * 
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * 
+ */
+package org.apache.cassandra.db.marshal;
+
+import java.net.InetAddress;
+import java.nio.ByteBuffer;
+
+import org.apache.cassandra.db.ColumnFamily;
+import org.apache.cassandra.db.CounterColumn;
+import org.apache.cassandra.db.Column;
+import org.apache.cassandra.db.DeletedColumn;
+import org.apache.cassandra.db.IColumn;
+import org.apache.cassandra.db.IColumnContainer;
+import org.apache.cassandra.db.SuperColumn;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.FBUtilities;
+
+public class CounterColumnType extends AbstractCommutativeType
+{
+    public static final CounterColumnType instance = new CounterColumnType();
+
+    CounterColumnType() {} // singleton
+
+    public int compare(ByteBuffer o1, ByteBuffer o2)
+    {
+        if (o1.remaining() == 0)
+        {
+            return o2.remaining() == 0 ? 0 : -1;
+        }
+        if (o2.remaining() == 0)
+        {
+            return 1;
+        }
+
+        return ByteBufferUtil.compareUnsigned(o1, o2);
+    }
+
+    public String getString(ByteBuffer bytes)
+    {
+        if (bytes.remaining() == 0)
+        {
+            return "";
+        }
+        if (bytes.remaining() != 8)
+        {
+            throw new MarshalException("A long is exactly 8 bytes");
+        }
+        return String.valueOf(bytes.getLong(bytes.position()+bytes.arrayOffset()));
+    }
+
+    /**
+     * create commutative column
+     */
+    public Column createColumn(ByteBuffer name, ByteBuffer value, long timestamp)
+    {
+        return new CounterColumn(name, value, timestamp);
+    }
+
+    /**
+     * update commutative columns for target node
+     */
+    public void update(IColumnContainer cc, InetAddress node)
+    {
+        for (IColumn column : cc.getSortedColumns())
+        {
+            if (column instanceof SuperColumn)
+            {
+                update((IColumnContainer)column, node);
+                continue;
+            }
+            
+            if (column instanceof DeletedColumn)
+                continue;
+            
+            ((CounterColumn)column).update(node);
+        }
+    }
+
+    /**
+     * remove target node from commutative columns
+     */
+    public void cleanContext(IColumnContainer cc, InetAddress node)
+    {
+        if ((cc instanceof ColumnFamily) && ((ColumnFamily)cc).isSuper())
+        {
+            for (IColumn column : cc.getSortedColumns())
+            {
+                SuperColumn supercol = (SuperColumn)column;
+                cleanContext(supercol, node);
+                if (0 == supercol.getSubColumns().size())
+                    cc.remove(supercol.name());
+            }
+            return;
+        }
+
+        for (IColumn column : cc.getSortedColumns())
+        {
+            CounterColumn counterColumn = (CounterColumn)column;
+            CounterColumn cleanedColumn = counterColumn.cleanNodeCounts(node);
+            if (cleanedColumn == counterColumn)
+                continue;
+            cc.remove(counterColumn.name());
+            //XXX: on "clean," must copy-and-replace
+            if (null != cleanedColumn)
+                cc.addColumn(cleanedColumn);
+        }
+    }
+
+    public void validate(ByteBuffer bytes) throws MarshalException
+    {
+        if (bytes.remaining() != 8 && bytes.remaining() != 0)
+            throw new MarshalException(String.format("Expected 8 or 0 byte long (%d)", bytes.remaining()));
+    }
+}
+

Modified: cassandra/trunk/src/java/org/apache/cassandra/dht/BootStrapper.java
URL: http://svn.apache.org/viewvc/cassandra/trunk/src/java/org/apache/cassandra/dht/BootStrapper.java?rev=1051679&r1=1051678&r2=1051679&view=diff
==============================================================================
--- cassandra/trunk/src/java/org/apache/cassandra/dht/BootStrapper.java (original)
+++ cassandra/trunk/src/java/org/apache/cassandra/dht/BootStrapper.java Tue Dec 21 22:17:09 2010
@@ -45,6 +45,7 @@ package org.apache.cassandra.dht;
  import org.apache.cassandra.net.Message;
  import org.apache.cassandra.net.MessagingService;
  import org.apache.cassandra.service.StorageService;
+ import org.apache.cassandra.streaming.OperationType;
  import org.apache.cassandra.streaming.StreamIn;
  import org.apache.cassandra.utils.FBUtilities;
  import org.apache.cassandra.utils.SimpleCondition;
@@ -107,8 +108,8 @@ public class BootStrapper
                     }
                 };
                 if (logger.isDebugEnabled())
-                    logger.debug("Bootstrapping from " + source + " ranges " + StringUtils.join(ranges, ", "));
-                StreamIn.requestRanges(source, table, ranges, callback);
+                    logger.debug("Bootstrapping from " + source + " ranges " + StringUtils.join(entry.getValue(), ", "));
+                StreamIn.requestRanges(source, table, entry.getValue(), callback, OperationType.BOOTSTRAP);
             }
         }