~pbeaman/akiban-persistit/accelerate-pruning

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/**
 * Copyright © 2011-2012 Akiban Technologies, Inc.  All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 (only) of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * This program may also be available under different license terms. For more
 * information, see www.akiban.com or contact licensing@akiban.com.
 */

package com.persistit;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

import com.persistit.Accumulator.Delta;

class TransactionStatus {

    /**
     * Distinguished commit timestamp for any value that has become primordial,
     * meaning that there are no longer any active concurrent transactions.
     */
    final static long PRIMORDIAL = 0;

    /**
     * Distinguished commit timestamp for any value created by a transaction
     * which subsequently aborted.
     */
    final static long ABORTED = Long.MIN_VALUE;

    /**
     * Distinguished commit timestamp for any value created by a transaction
     * that is still running.
     */
    final static long UNCOMMITTED = Long.MAX_VALUE;

    /**
     * Distinguished synthetic timestamp signifying that a thread waiting for a
     * stable result timed out.
     */
    final static long TIMED_OUT = Long.MIN_VALUE + 1;

    /**
     * The bucket to which this <code>TransactionStatus</code> belongs.
     */
    private final TransactionIndexBucket _bucket;
    /**
     * Start timestamp. This value may only be assigned by
     * {@link TransactionIndex#registerTransaction(Transaction)}.
     */
    private volatile long _ts;

    /**
     * Commit timestamp and status. Value is one of
     * <dl>
     * <dt>PRIMORDIAL</dt>
     * <dd>The transaction committed long ago, meaning before any concurrent
     * activity. A TrasactionStatus will never have this value, but it is used
     * in other places to communicate the fact that a transaction committed
     * before any recent history.</dd>
     * <dt>ABORTED</dt>
     * <dd>the transaction aborted.</dd>
     * <dt>UNCOMMITTED</dt>
     * <dd>The transaction is running and has not yet asked to commit.</dd>
     * <dt>v &lt; 0</dt>
     * <dd>Any negative value other than Long.MIN_VALUE indicates the timestamp
     * value at which the transaction started to commit; the commit process is
     * incomplete.</dd>
     * <dt>v &gt; 0</dt>
     * <dd>Any positive value other than Long.MAX_VALUE indicates the commit
     * timestamp; the transaction commit is complete.</dd>
     * </dl>
     */
    private volatile long _tc;

    /**
     * Timestamp at which the last MMV version written by this transaction has
     * been pruned (if the transaction aborted). The
     * <code>TransactionStatus</code> may not be removed until there are no
     * currently active transactions have start timestamps older than this
     * value.
     */
    private volatile long _ta;

    /**
     * Count of MVV versions created by associated transaction.
     */
    private AtomicInteger _mvvCount = new AtomicInteger();

    /**
     * Lock used to manage ww dependencies. An attempt to update an MVV that
     * already contains a value version from a concurrently executing
     * transaction must wait for that other transaction to commit or abort.
     */
    private ReentrantLock _wwLock = new ReentrantLock(true);
    /**
     * Pointer to next member of singly-linked list.
     */
    private TransactionStatus _next;

    /**
     * Pointer to TransactionStatus on which we intend to claim a lock. (For
     * deadlock detection.)
     */
    private volatile TransactionStatus _depends;

    /**
     * Pointer to first member of a list of Delta instances contributed through
     * the associated transaction.
     */
    private volatile Delta _delta;

    /**
     * Indicates whether the transaction has called
     * {@link TransactionIndexBucket#notifyCompleted(long)}. Until then the
     * <code>TransactionStatus</code> may not be placed on the free list.
     */
    private boolean _notified;

    TransactionStatus(final TransactionIndexBucket bucket) {
        _bucket = bucket;
    }
    
    /**
     * Constructs a partial copy. Used only in diagnostic code.
     * @param status
     */
    TransactionStatus(final TransactionStatus status) {
        this._bucket = status._bucket;
        this._mvvCount = status._mvvCount;
        this._notified = status._notified;
        this._ta = status._ta;
        this._tc = status._tc;
        this._ts = status._ts;
    }

    /**
     * @return The next TransactionStatus on linked list, or <code>null</code>
     *         if there is none
     */
    TransactionStatus getNext() {
        return _next;
    }

    /**
     * Link another TransactionStatus to this one.
     * 
     * @param next
     *            the TransactionStatus to link
     */
    void setNext(final TransactionStatus next) {
        _next = next;
    }

    /**
     * @return The next TransactionStatus on dependency linked list, or
     *         <code>null</code> if there is none
     */
    TransactionStatus getDepends() {
        return _depends;
    }

    /**
     * Link another TransactionStatus this one depends on.
     * 
     * @param next
     *            the TransactionStatus to link
     */
    void setDepends(final TransactionStatus depends) {
        _depends = depends;
    }

    /**
     * 
     * @return The associated transaction's start timestamp
     */
    long getTs() {
        return _ts;
    }

    /**
     * @return the commit status of the associated transaction.
     */
    long getTc() {
        return _tc;
    }

    /**
     * @return the abort cleanup timestamp
     */
    long getTa() {
        return _ta;
    }

    /**
     * @return whether the {@link TransactionIndexBucket#notifyCompleted(long)}
     *         has been called.
     */
    boolean isNotified() {
        return _notified;
    }
    
    /**
     * Start commit processing. This method leaves the
     * <code>TransactionStatus</code> in a state indicating commit processing is
     * underway. The {@link #commit(long)} method completes the process. Note
     * that until we implement SSI this method is unnecessary, but is included
     * so that unit tests can test the interim state.
     * 
     * @param timestamp
     */
    void commit(final long timestamp) {
        if (timestamp < _ts || timestamp == UNCOMMITTED) {
            throw new IllegalArgumentException("Attempt to commit before start: " + this);
        }
        if (_tc != UNCOMMITTED) {
            throw new IllegalArgumentException("Already committed or aborted: " + this);
        }
        _tc = -timestamp;
    }

    void abort() {
        if (_tc != UNCOMMITTED) {
            throw new IllegalArgumentException("Already committed or aborted: " + this);
        }
        _tc = ABORTED;
    }
    
    void complete(final long timestamp) {
        if (_tc > 0 || -_tc > timestamp && timestamp != ABORTED) {
            throw new IllegalStateException("Transaction not ready to complete: " + this);
        }
        if (_tc < 0 && _tc != ABORTED) {
            _tc = timestamp;
        }
        _notified = true;
    }
    
    boolean isLocked() {
        return _wwLock.isLocked();
    }
    
    boolean isHeldByCurrentThread() {
        return _wwLock.isHeldByCurrentThread();
    }

    Delta getDelta() {
        return _delta;
    }

    void addDelta(final Delta delta) {
        delta.setNext(_delta);
        _delta = delta;
    }

    Delta takeDelta() {
        final Delta delta = _delta;
        _delta = null;
        return delta;
    }

    long accumulate(final long value, final Accumulator accumulator, final int step) {
        long result = value;
        for (Delta delta = _delta; delta != null; delta = delta.getNext()) {
            if (delta.getAccumulator() == accumulator && delta.getStep() < step) {
                result = accumulator.applyValue(result, delta.getValue());
            }
        }
        return result;
    }

    /**
     * Increment the count of MVV modifications made by the associated
     * transaction. This is done each time a transaction modifies a value. The
     * counter is used to determine when all values modified by an aborted
     * transaction have been pruned.
     * 
     * @return the updated count
     */
    int incrementMvvCount() {
        _ta = Long.MAX_VALUE;
        return _mvvCount.incrementAndGet();
    }

    /**
     * Decrement the count of MVV modifications made by the associated
     * transaction. This is done each time a version is removed by pruning. When
     * the count becomes zero, then if the associated transaction aborted its
     * TransactionStatus can be removed from the abort set.
     * 
     * @return the updated count
     */
    int decrementMvvCount() {
        assert _tc == ABORTED : "can only decrement MVVs for an aborted transaction";
        int count = _mvvCount.decrementAndGet();
        assert count >= 0: "mvvCount is negative";
        if (count == 0) {
            _ta = _bucket.getTimestampAllocator().getCurrentTimestamp();
        }
        return count;
    }

    /**
     * @return The count of MVV modifications made by the associated
     *         transaction.
     */
    int getMvvCount() {
        return _mvvCount.get();
    }

    /**
     * Sets the MVV modification count. In recovery, this is initially set to
     * Integer.MAX_VALUE to prevent pruning code from removing aborted
     * transactions from the abort set prematurely. Note that we do not attempt
     * to recover an accurate count after a crash.
     */
    void setMvvCount(final int count) {
        _mvvCount.set(count);
    }

    /**
     * <p>
     * Acquire a lock on this TransactionStatus. This supports the
     * {@link TransactionIndex#wwDependency(long, long, long)} method. While a
     * transaction is running this lock is in a locked state. The lock is
     * acquired when the transaction is registered (see
     * {@link TransactionIndex#registerTransaction(Transaction)} and released
     * once the transaction is either committed or aborted.
     * </p>
     * <p>
     * The <code>wwDependency</code> method also attempts to acquire, and then
     * immediately release this lock. This stalls the thread calling
     * wwDependency until the commit/abort status of the current transaction is
     * known.
     * 
     * @param timeout
     * @return
     * @throws InterruptedException
     */
    boolean wwLock(final long timeout) throws InterruptedException {
        return _wwLock.tryLock(timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * Release the lock acquired by {@link #wwLock(long)}.
     */
    void wwUnlock() {
        _wwLock.unlock();
    }

    /**
     * Initialize this <code>TransactionStatus</code> instance for a new
     * transaction.
     * 
     * @param ts Start time of this status.
     */
    void initialize(final long ts) {
        _ts = ts;
        _tc = UNCOMMITTED;
        _ta = PRIMORDIAL;
        _next = null;
        _delta = null;
        _mvvCount.set(0);
        _notified = false;
    }

    /**
     * Initialize this <code>TransactionStatus</code> instance for an
     * artificial transaction known to be aborted. The initial state
     * is aborted, infinite MVV count, and notified.
     *
     * @param ts Start time of this status.
     */
    void initializeAsAborted(final long ts) {
        initialize(ts);
        abort();
        setMvvCount(Integer.MAX_VALUE);
        _notified = true;
    }

    @Override
    public String toString() {
        return String.format("<ts=%,d tc=%s mvv=%,d>", _ts, tcString(_tc), _mvvCount.get());
    }

    static String versionString(final long version) {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("%,d", TransactionIndex.vh2ts(version)));
        int step = TransactionIndex.vh2step(version);
        if (step > 0) {
            sb.append(String.format("#%02d", step));
        }
        return sb.toString();
    }
    
    static String tcString(final long ts) {
        if (ts == ABORTED) {
            return "ABORTED";
        } else if (ts == UNCOMMITTED) {
            return "UNCOMMITTED";
        } else {
            return String.format("%,d", ts);
        }
    }
}