xref: /JGit/Documentation/technical/reftable.md (revision c217d33ff89bc39b084e4269cf0255a5d4a9ae93)
1# reftable
2
3[TOC]
4
5## Overview
6
7### Problem statement
8
9Some repositories contain a lot of references (e.g.  android at 866k,
10rails at 31k).  The existing packed-refs format takes up a lot of
11space (e.g.  62M), and does not scale with additional references.
12Lookup of a single reference requires linearly scanning the file.
13
14Atomic pushes modifying multiple references require copying the
15entire packed-refs file, which can be a considerable amount of data
16moved (e.g. 62M in, 62M out) for even small transactions (2 refs
17modified).
18
19Repositories with many loose references occupy a large number of disk
20blocks from the local file system, as each reference is its own file
21storing 41 bytes (and another file for the corresponding reflog).
22This negatively affects the number of inodes available when a large
23number of repositories are stored on the same filesystem.  Readers can
24be penalized due to the larger number of syscalls required to traverse
25and read the `$GIT_DIR/refs` directory.
26
27### Objectives
28
29- Near constant time lookup for any single reference, even when the
30  repository is cold and not in process or kernel cache.
31- Near constant time verification if a SHA-1 is referred to by at
32  least one reference (for allow-tip-sha1-in-want).
33- Efficient lookup of an entire namespace, such as `refs/tags/`.
34- Support atomic push with `O(size_of_update)` operations.
35- Combine reflog storage with ref storage for small transactions.
36- Separate reflog storage for base refs and historical logs.
37
38### Description
39
40A reftable file is a portable binary file format customized for
41reference storage. References are sorted, enabling linear scans,
42binary search lookup, and range scans.
43
44Storage in the file is organized into variable sized blocks.  Prefix
45compression is used within a single block to reduce disk space.  Block
46size and alignment is tunable by the writer.
47
48### Performance
49
50Space used, packed-refs vs. reftable:
51
52repository | packed-refs | reftable | % original | avg ref  | avg obj
53-----------|------------:|---------:|-----------:|---------:|--------:
54android    |      62.2 M |   36.1 M |     58.0%  | 33 bytes | 5 bytes
55rails      |       1.8 M |    1.1 M |     57.7%  | 29 bytes | 4 bytes
56git        |      78.7 K |   48.1 K |     61.0%  | 50 bytes | 4 bytes
57git (heads)|       332 b |    269 b |     81.0%  | 33 bytes | 0 bytes
58
59Scan (read 866k refs), by reference name lookup (single ref from 866k
60refs), and by SHA-1 lookup (refs with that SHA-1, from 866k refs):
61
62format      | cache | scan    | by name        | by SHA-1
63------------|------:|--------:|---------------:|---------------:
64packed-refs | cold  |  402 ms | 409,660.1 usec | 412,535.8 usec
65packed-refs | hot   |         |   6,844.6 usec |  20,110.1 usec
66reftable    | cold  |  112 ms |      33.9 usec |     323.2 usec
67reftable    | hot   |         |      20.2 usec |     320.8 usec
68
69Space used for 149,932 log entries for 43,061 refs,
70reflog vs. reftable:
71
72format        | size  | avg entry
73--------------|------:|-----------:
74$GIT_DIR/logs | 173 M | 1209 bytes
75reftable      |   5 M |   37 bytes
76
77## Details
78
79### Peeling
80
81References stored in a reftable are peeled, a record for an annotated
82(or signed) tag records both the tag object, and the object it refers
83to.
84
85### Reference name encoding
86
87Reference names are an uninterpreted sequence of bytes that must pass
88[git-check-ref-format][ref-fmt] as a valid reference name.
89
90[ref-fmt]: https://git-scm.com/docs/git-check-ref-format
91
92### Key unicity
93
94Each entry must have a unique key; repeated keys are disallowed.
95
96### Network byte order
97
98All multi-byte, fixed width fields are in network byte order.
99
100### Ordering
101
102Blocks are lexicographically ordered by their first reference.
103
104### Directory/file conflicts
105
106The reftable format accepts both `refs/heads/foo` and
107`refs/heads/foo/bar` as distinct references.
108
109This property is useful for retaining log records in reftable, but may
110confuse versions of Git using `$GIT_DIR/refs` directory tree to
111maintain references.  Users of reftable may choose to continue to
112reject `foo` and `foo/bar` type conflicts to prevent problems for
113peers.
114
115## File format
116
117### Structure
118
119A reftable file has the following high-level structure:
120
121    first_block {
122      header
123      first_ref_block
124    }
125    ref_block*
126    ref_index*
127    obj_block*
128    obj_index*
129    log_block*
130    log_index*
131    footer
132
133A log-only file omits the `ref_block`, `ref_index`, `obj_block` and
134`obj_index` sections, containing only the file header and log block:
135
136    first_block {
137      header
138    }
139    log_block*
140    log_index*
141    footer
142
143in a log-only file the first log block immediately follows the file
144header, without padding to block alignment.
145
146### Block size
147
148The file's block size is arbitrarily determined by the writer, and
149does not have to be a power of 2.  The block size must be larger than
150the longest reference name or log entry used in the repository, as
151references cannot span blocks.
152
153Powers of two that are friendly to the virtual memory system or
154filesystem (such as 4k or 8k) are recommended.  Larger sizes (64k) can
155yield better compression, with a possible increased cost incurred by
156readers during access.
157
158The largest block size is `16777215` bytes (15.99 MiB).
159
160### Block alignment
161
162Writers may choose to align blocks at multiples of the block size by
163including `padding` filled with NUL bytes at the end of a block to
164round out to the chosen alignment.  When alignment is used, writers
165must specify the alignment with the file header's `block_size` field.
166
167Block alignment is not required by the file format.  Unaligned files
168must set `block_size = 0` in the file header, and omit `padding`.
169Unaligned files with more than one ref block must include the
170[ref index](#Ref-index) to support fast lookup.  Readers must be
171able to read both aligned and non-aligned files.
172
173Very small files (e.g. 1 only ref block) may omit `padding` and the
174ref index to reduce total file size.
175
176### Header
177
178A 24-byte header appears at the beginning of the file:
179
180    'REFT'
181    uint8( version_number = 1 )
182    uint24( block_size )
183    uint64( min_update_index )
184    uint64( max_update_index )
185
186Aligned files must specify `block_size` to configure readers with the
187expected block alignment.  Unaligned files must set `block_size = 0`.
188
189The `min_update_index` and `max_update_index` describe bounds for the
190`update_index` field of all log records in this file.  When reftables
191are used in a stack for [transactions](#Update-transactions), these
192fields can order the files such that the prior file's
193`max_update_index + 1` is the next file's `min_update_index`.
194
195### First ref block
196
197The first ref block shares the same block as the file header, and is
19824 bytes smaller than all other blocks in the file.  The first block
199immediately begins after the file header, at position 24.
200
201If the first block is a log block (a log-only file), its block header
202begins immediately at position 24.
203
204### Ref block format
205
206A ref block is written as:
207
208    'r'
209    uint24( block_len )
210    ref_record+
211    uint24( restart_offset )+
212    uint16( restart_count )
213
214    padding?
215
216Blocks begin with `block_type = 'r'` and a 3-byte `block_len` which
217encodes the number of bytes in the block up to, but not including the
218optional `padding`.  This is always less than or equal to the file's
219block size.  In the first ref block, `block_len` includes 24 bytes
220for the file header.
221
222The 2-byte `restart_count` stores the number of entries in the
223`restart_offset` list, which must not be empty.  Readers can use
224`restart_count` to binary search between restarts before starting a
225linear scan.
226
227Exactly `restart_count` 3-byte `restart_offset` values precedes the
228`restart_count`.  Offsets are relative to the start of the block and
229refer to the first byte of any `ref_record` whose name has not been
230prefix compressed.  Entries in the `restart_offset` list must be
231sorted, ascending.  Readers can start linear scans from any of these
232records.
233
234A variable number of `ref_record` fill the middle of the block,
235describing reference names and values.  The format is described below.
236
237As the first ref block shares the first file block with the file
238header, all `restart_offset` in the first block are relative to the
239start of the file (position 0), and include the file header.  This
240forces the first `restart_offset` to be `28`.
241
242#### ref record
243
244A `ref_record` describes a single reference, storing both the name and
245its value(s). Records are formatted as:
246
247    varint( prefix_length )
248    varint( (suffix_length << 3) | value_type )
249    suffix
250    varint( update_index_delta )
251    value?
252
253The `prefix_length` field specifies how many leading bytes of the
254prior reference record's name should be copied to obtain this
255reference's name.  This must be 0 for the first reference in any
256block, and also must be 0 for any `ref_record` whose offset is listed
257in the `restart_offset` table at the end of the block.
258
259Recovering a reference name from any `ref_record` is a simple concat:
260
261    this_name = prior_name[0..prefix_length] + suffix
262
263The `suffix_length` value provides the number of bytes available in
264`suffix` to copy from `suffix` to complete the reference name.
265
266The `update_index` that last modified the reference can be obtained by
267adding `update_index_delta` to the `min_update_index` from the file
268header: `min_update_index + update_index_delta`.
269
270The `value` follows.  Its format is determined by `value_type`, one of
271the following:
272
273- `0x0`: deletion; no value data (see transactions, below)
274- `0x1`: one 20-byte object id; value of the ref
275- `0x2`: two 20-byte object ids; value of the ref, peeled target
276- `0x3`: symbolic reference: `varint( target_len ) target`
277
278Symbolic references use `0x3`, followed by the complete name of the
279reference target.  No compression is applied to the target name.
280
281Types `0x4..0x7` are reserved for future use.
282
283### Ref index
284
285The ref index stores the name of the last reference from every ref
286block in the file, enabling reduced disk seeks for lookups.  Any
287reference can be found by searching the index, identifying the
288containing block, and searching within that block.
289
290The index may be organized into a multi-level index, where the 1st
291level index block points to additional ref index blocks (2nd level),
292which may in turn point to either additional index blocks (e.g. 3rd
293level) or ref blocks (leaf level).  Disk reads required to access a
294ref go up with higher index levels.  Multi-level indexes may be
295required to ensure no single index block exceeds the file format's max
296block size of `16777215` bytes (15.99 MiB).  To acheive constant O(1)
297disk seeks for lookups the index must be a single level, which is
298permitted to exceed the file's configured block size, but not the
299format's max block size of 15.99 MiB.
300
301If present, the ref index block(s) appears after the last ref block.
302
303If there are at least 4 ref blocks, a ref index block should be
304written to improve lookup times.  Cold reads using the index require
3052 disk reads (read index, read block), and binary searching < 4 blocks
306also requires <= 2 reads.  Omitting the index block from smaller files
307saves space.
308
309If the file is unaligned and contains more than one ref block, the ref
310index must be written.
311
312Index block format:
313
314    'i'
315    uint24( block_len )
316    index_record+
317    uint24( restart_offset )+
318    uint16( restart_count )
319
320    padding?
321
322The index blocks begin with `block_type = 'i'` and a 3-byte
323`block_len` which encodes the number of bytes in the block,
324up to but not including the optional `padding`.
325
326The `restart_offset` and `restart_count` fields are identical in
327format, meaning and usage as in ref blocks.
328
329To reduce the number of reads required for random access in very large
330files the index block may be larger than other blocks.  However,
331readers must hold the entire index in memory to benefit from this, so
332it's a time-space tradeoff in both file size and reader memory.
333
334Increasing the file's block size decreases the index size.
335Alternatively a multi-level index may be used, keeping index blocks
336within the file's block size, but increasing the number of blocks
337that need to be accessed.
338
339#### index record
340
341An index record describes the last entry in another block.
342Index records are written as:
343
344    varint( prefix_length )
345    varint( (suffix_length << 3) | 0 )
346    suffix
347    varint( block_position )
348
349Index records use prefix compression exactly like `ref_record`.
350
351Index records store `block_position` after the suffix, specifying the
352absolute position in bytes (from the start of the file) of the block
353that ends with this reference. Readers can seek to `block_position` to
354begin reading the block header.
355
356Readers must examine the block header at `block_position` to determine
357if the next block is another level index block, or the leaf-level ref
358block.
359
360#### Reading the index
361
362Readers loading the ref index must first read the footer (below) to
363obtain `ref_index_position`. If not present, the position will be 0.
364The `ref_index_position` is for the 1st level root of the ref index.
365
366### Obj block format
367
368Object blocks are optional.  Writers may choose to omit object blocks,
369especially if readers will not use the SHA-1 to ref mapping.
370
371Object blocks use unique, abbreviated 2-20 byte SHA-1 keys, mapping
372to ref blocks containing references pointing to that object directly,
373or as the peeled value of an annotated tag.  Like ref blocks, object
374blocks use the file's standard block size. The abbrevation length is
375available in the footer as `obj_id_len`.
376
377To save space in small files, object blocks may be omitted if the ref
378index is not present, as brute force search will only need to read a
379few ref blocks.  When missing, readers should brute force a linear
380search of all references to lookup by SHA-1.
381
382An object block is written as:
383
384    'o'
385    uint24( block_len )
386    obj_record+
387    uint24( restart_offset )+
388    uint16( restart_count )
389
390    padding?
391
392Fields are identical to ref block.  Binary search using the restart
393table works the same as in reference blocks.
394
395Because object identifiers are abbreviated by writers to the shortest
396unique abbreviation within the reftable, obj key lengths are variable
397between 2 and 20 bytes.  Readers must compare only for common prefix
398match within an obj block or obj index.
399
400#### obj record
401
402An `obj_record` describes a single object abbreviation, and the blocks
403containing references using that unique abbreviation:
404
405    varint( prefix_length )
406    varint( (suffix_length << 3) | cnt_3 )
407    suffix
408    varint( cnt_large )?
409    varint( position_delta )*
410
411Like in reference blocks, abbreviations are prefix compressed within
412an obj block.  On large reftables with many unique objects, higher
413block sizes (64k), and higher restart interval (128), a
414`prefix_length` of 2 or 3 and `suffix_length` of 3 may be common in
415obj records (unique abbreviation of 5-6 raw bytes, 10-12 hex digits).
416
417Each record contains `position_count` number of positions for matching
418ref blocks.  For 1-7 positions the count is stored in `cnt_3`.  When
419`cnt_3 = 0` the actual count follows in a varint, `cnt_large`.
420
421The use of `cnt_3` bets most objects are pointed to by only a single
422reference, some may be pointed to by a couple of references, and very
423few (if any) are pointed to by more than 7 references.
424
425A special case exists when `cnt_3 = 0` and `cnt_large = 0`: there
426are no `position_delta`, but at least one reference starts with this
427abbreviation.  A reader that needs exact reference names must scan all
428references to find which specific references have the desired object.
429Writers should use this format when the `position_delta` list would have
430overflowed the file's block size due to a high number of references
431pointing to the same object.
432
433The first `position_delta` is the position from the start of the file.
434Additional `position_delta` entries are sorted ascending and relative
435to the prior entry, e.g.  a reader would perform:
436
437    pos = position_delta[0]
438    prior = pos
439    for (j = 1; j < position_count; j++) {
440      pos = prior + position_delta[j]
441      prior = pos
442    }
443
444With a position in hand, a reader must linearly scan the ref block,
445starting from the first `ref_record`, testing each reference's SHA-1s
446(for `value_type = 0x1` or `0x2`) for full equality.  Faster searching
447by SHA-1 within a single ref block is not supported by the reftable
448format.  Smaller block sizes reduce the number of candidates this step
449must consider.
450
451### Obj index
452
453The obj index stores the abbreviation from the last entry for every
454obj block in the file, enabling reduced disk seeks for all lookups.
455It is formatted exactly the same as the ref index, but refers to obj
456blocks.
457
458The obj index should be present if obj blocks are present, as
459obj blocks should only be written in larger files.
460
461Readers loading the obj index must first read the footer (below) to
462obtain `obj_index_position`.  If not present, the position will be 0.
463
464### Log block format
465
466Unlike ref and obj blocks, log blocks are always unaligned.
467
468Log blocks are variable in size, and do not match the `block_size`
469specified in the file header or footer.  Writers should choose an
470appropriate buffer size to prepare a log block for deflation, such as
471`2 * block_size`.
472
473A log block is written as:
474
475    'g'
476    uint24( block_len )
477    zlib_deflate {
478      log_record+
479      uint24( restart_offset )+
480      uint16( restart_count )
481    }
482
483Log blocks look similar to ref blocks, except `block_type = 'g'`.
484
485The 4-byte block header is followed by the deflated block contents
486using zlib deflate.  The `block_len` in the header is the inflated
487size (including 4-byte block header), and should be used by readers to
488preallocate the inflation output buffer.  A log block's `block_len`
489may exceed the file's block size.
490
491Offsets within the log block (e.g.  `restart_offset`) still include
492the 4-byte header.  Readers may prefer prefixing the inflation output
493buffer with the 4-byte header.
494
495Within the deflate container, a variable number of `log_record`
496describe reference changes.  The log record format is described
497below.  See ref block format (above) for a description of
498`restart_offset` and `restart_count`.
499
500Because log blocks have no alignment or padding between blocks,
501readers must keep track of the bytes consumed by the inflater to
502know where the next log block begins.
503
504#### log record
505
506Log record keys are structured as:
507
508    ref_name '\0' reverse_int64( update_index )
509
510where `update_index` is the unique transaction identifier.  The
511`update_index` field must be unique within the scope of a `ref_name`.
512See the update transactions section below for further details.
513
514The `reverse_int64` function inverses the value so lexographical
515ordering the network byte order encoding sorts the more recent records
516with higher `update_index` values first:
517
518    reverse_int64(int64 t) {
519      return 0xffffffffffffffff - t;
520    }
521
522Log records have a similar starting structure to ref and index
523records, utilizing the same prefix compression scheme applied to the
524log record key described above.
525
526```
527    varint( prefix_length )
528    varint( (suffix_length << 3) | log_type )
529    suffix
530    log_data {
531      old_id
532      new_id
533      varint( name_length    )  name
534      varint( email_length   )  email
535      varint( time_seconds )
536      sint16( tz_offset )
537      varint( message_length )  message
538    }?
539```
540
541Log record entries use `log_type` to indicate what follows:
542
543- `0x0`: deletion; no log data.
544- `0x1`: standard git reflog data using `log_data` above.
545
546The `log_type = 0x0` is mostly useful for `git stash drop`, removing
547an entry from the reflog of `refs/stash` in a transaction file
548(below), without needing to rewrite larger files.  Readers reading a
549stack of reflogs must treat this as a deletion.
550
551For `log_type = 0x1`, the `log_data` section follows
552[git update-ref][update-ref] logging, and includes:
553
554- two 20-byte SHA-1s (old id, new id)
555- varint string of committer's name
556- varint string of committer's email
557- varint time in seconds since epoch (Jan 1, 1970)
558- 2-byte timezone offset in minutes (signed)
559- varint string of message
560
561`tz_offset` is the absolute number of minutes from GMT the committer
562was at the time of the update.  For example `GMT-0800` is encoded in
563reftable as `sint16(-480)` and `GMT+0230` is `sint16(150)`.
564
565The committer email does not contain `<` or `>`, it's the value
566normally found between the `<>` in a git commit object header.
567
568The `message_length` may be 0, in which case there was no message
569supplied for the update.
570
571[update-ref]: https://git-scm.com/docs/git-update-ref#_logging_updates
572
573Contrary to traditional reflog (which is a file), renames are encoded as a
574combination of ref deletion and ref creation.
575
576
577#### Reading the log
578
579Readers accessing the log must first read the footer (below) to
580determine the `log_position`.  The first block of the log begins at
581`log_position` bytes since the start of the file.  The `log_position`
582is not block aligned.
583
584#### Importing logs
585
586When importing from `$GIT_DIR/logs` writers should globally order all
587log records roughly by timestamp while preserving file order, and
588assign unique, increasing `update_index` values for each log line.
589Newer log records get higher `update_index` values.
590
591Although an import may write only a single reftable file, the reftable
592file must span many unique `update_index`, as each log line requires
593its own `update_index` to preserve semantics.
594
595### Log index
596
597The log index stores the log key (`refname \0 reverse_int64(update_index)`)
598for the last log record of every log block in the file, supporting
599bounded-time lookup.
600
601A log index block must be written if 2 or more log blocks are written
602to the file.  If present, the log index appears after the last log
603block.  There is no padding used to align the log index to block
604alignment.
605
606Log index format is identical to ref index, except the keys are 9
607bytes longer to include `'\0'` and the 8-byte
608`reverse_int64(update_index)`.  Records use `block_position` to
609refer to the start of a log block.
610
611#### Reading the index
612
613Readers loading the log index must first read the footer (below) to
614obtain `log_index_position`. If not present, the position will be 0.
615
616### Footer
617
618After the last block of the file, a file footer is written.  It begins
619like the file header, but is extended with additional data.
620
621A 68-byte footer appears at the end:
622
623```
624    'REFT'
625    uint8( version_number = 1 )
626    uint24( block_size )
627    uint64( min_update_index )
628    uint64( max_update_index )
629
630    uint64( ref_index_position )
631    uint64( (obj_position << 5) | obj_id_len )
632    uint64( obj_index_position )
633
634    uint64( log_position )
635    uint64( log_index_position )
636
637    uint32( CRC-32 of above )
638```
639
640If a section is missing (e.g. ref index) the corresponding position
641field (e.g. `ref_index_position`) will be 0.
642
643- `obj_position`: byte position for the first obj block.
644- `obj_id_len`: number of bytes used to abbreviate object identifiers
645  in obj blocks.
646- `log_position`: byte position for the first log block.
647- `ref_index_position`: byte position for the start of the ref index.
648- `obj_index_position`: byte position for the start of the obj index.
649- `log_index_position`: byte position for the start of the log index.
650
651#### Reading the footer
652
653Readers must seek to `file_length - 68` to access the footer.  A
654trusted external source (such as `stat(2)`) is necessary to obtain
655`file_length`.  When reading the footer, readers must verify:
656
657- 4-byte magic is correct
658- 1-byte version number is recognized
659- 4-byte CRC-32 matches the other 64 bytes (including magic, and version)
660
661Once verified, the other fields of the footer can be accessed.
662
663### Varint encoding
664
665Varint encoding is identical to the ofs-delta encoding method used
666within pack files.
667
668Decoder works such as:
669
670    val = buf[ptr] & 0x7f
671    while (buf[ptr] & 0x80) {
672      ptr++
673      val = ((val + 1) << 7) | (buf[ptr] & 0x7f)
674    }
675
676### Binary search
677
678Binary search within a block is supported by the `restart_offset`
679fields at the end of the block.  Readers can binary search through the
680restart table to locate between which two restart points the sought
681reference or key should appear.
682
683Each record identified by a `restart_offset` stores the complete key
684in the `suffix` field of the record, making the compare operation
685during binary search straightforward.
686
687Once a restart point lexicographically before the sought reference has
688been identified, readers can linearly scan through the following
689record entries to locate the sought record, terminating if the current
690record sorts after (and therefore the sought key is not present).
691
692#### Restart point selection
693
694Writers determine the restart points at file creation.  The process is
695arbitrary, but every 16 or 64 records is recommended.  Every 16 may
696be more suitable for smaller block sizes (4k or 8k), every 64 for
697larger block sizes (64k).
698
699More frequent restart points reduces prefix compression and increases
700space consumed by the restart table, both of which increase file size.
701
702Less frequent restart points makes prefix compression more effective,
703decreasing overall file size, with increased penalities for readers
704walking through more records after the binary search step.
705
706A maximum of `65535` restart points per block is supported.
707
708## Considerations
709
710### Lightweight refs dominate
711
712The reftable format assumes the vast majority of references are single
713SHA-1 valued with common prefixes, such as Gerrit Code Review's
714`refs/changes/` namespace, GitHub's `refs/pulls/` namespace, or many
715lightweight tags in the `refs/tags/` namespace.
716
717Annotated tags storing the peeled object cost an additional 20 bytes
718per reference.
719
720### Low overhead
721
722A reftable with very few references (e.g. git.git with 5 heads)
723is 269 bytes for reftable, vs. 332 bytes for packed-refs.  This
724supports reftable scaling down for transaction logs (below).
725
726### Block size
727
728For a Gerrit Code Review type repository with many change refs, larger
729block sizes (64 KiB) and less frequent restart points (every 64) yield
730better compression due to more references within the block compressing
731against the prior reference.
732
733Larger block sizes reduce the index size, as the reftable will
734require fewer blocks to store the same number of references.
735
736### Minimal disk seeks
737
738Assuming the index block has been loaded into memory, binary searching
739for any single reference requires exactly 1 disk seek to load the
740containing block.
741
742### Scans and lookups dominate
743
744Scanning all references and lookup by name (or namespace such as
745`refs/heads/`) are the most common activities performed on repositories.
746SHA-1s are stored directly with references to optimize this use case.
747
748### Logs are infrequently read
749
750Logs are infrequently accessed, but can be large.  Deflating log
751blocks saves disk space, with some increased penalty at read time.
752
753Logs are stored in an isolated section from refs, reducing the burden
754on reference readers that want to ignore logs.  Further, historical
755logs can be isolated into log-only files.
756
757### Logs are read backwards
758
759Logs are frequently accessed backwards (most recent N records for
760master to answer `master@{4}`), so log records are grouped by
761reference, and sorted descending by update index.
762
763## Repository format
764
765### Version 1
766
767A repository must set its `$GIT_DIR/config` to configure reftable:
768
769    [core]
770        repositoryformatversion = 1
771    [extensions]
772        refStorage = reftable
773
774### Layout
775
776A collection of reftable files are stored in the `$GIT_DIR/reftable/`
777directory:
778
779    00000001-00000001.log
780    00000002-00000002.ref
781    00000003-00000003.ref
782
783where reftable files are named by a unique name such as produced by
784the function `${min_update_index}-${max_update_index}.ref`.
785
786Log-only files use the `.log` extension, while ref-only and mixed ref
787and log files use `.ref`.  extension.
788
789
790The stack ordering file is `$GIT_DIR/reftable/tables.list` and lists the current
791files, one per line, in order, from oldest (base) to newest (most recent):
792
793    $ cat .git/reftable/tables.list
794    00000001-00000001.log
795    00000002-00000002.ref
796    00000003-00000003.ref
797
798Readers must read `$GIT_DIR/reftable/tables.list` to determine which files are
799relevant right now, and search through the stack in reverse order (last reftable
800is examined first).
801
802Reftable files not listed in `tables.list` may be new (and about to be added
803to the stack by the active writer), or ancient and ready to be pruned.
804
805### Backward compatibility
806
807Older clients should continue to recognize the directory as a git repository so
808they don't look for an enclosing repository in parent directories. To this end,
809a reftable-enabled repository must contain the following dummy files
810
811*   `.git/HEAD`, a regular file containing `ref: refs/heads/.invalid`.
812*   `.git/refs/`, a directory
813*   `.git/refs/heads`, a regular file
814
815### Readers
816
817Readers can obtain a consistent snapshot of the reference space by
818following:
819
8201.  Open and read the `tables.list` file.
8212.  Open each of the reftable files that it mentions.
8223.  If any of the files is missing, goto 1.
8234.  Read from the now-open files as long as necessary.
824
825### Update transactions
826
827Although reftables are immutable, mutations are supported by writing a
828new reftable and atomically appending it to the stack:
829
8301. Acquire `tables.list.lock`.
8312. Read `tables.list` to determine current reftables.
8323. Select `update_index` to be most recent file's `max_update_index + 1`.
8334. Prepare temp reftable `tmp_XXXXXX`, including log entries.
8345. Rename `tmp_XXXXXX` to `${update_index}-${update_index}.ref`.
8356. Copy `tables.list` to `tables.list.lock`, appending file from (5).
8367. Rename `tables.list.lock` to `tables.list`.
837
838During step 4 the new file's `min_update_index` and `max_update_index`
839are both set to the `update_index` selected by step 3.  All log
840records for the transaction use the same `update_index` in their keys.
841This enables later correlation of which references were updated by the
842same transaction.
843
844Because a single `tables.list.lock` file is used to manage locking, the
845repository is single-threaded for writers.  Writers may have to
846busy-spin (with backoff) around creating `tables.list.lock`, for up to an
847acceptable wait period, aborting if the repository is too busy to
848mutate.  Application servers wrapped around repositories (e.g.  Gerrit
849Code Review) can layer their own lock/wait queue to improve fairness
850to writers.
851
852### Reference deletions
853
854Deletion of any reference can be explicitly stored by setting the
855`type` to `0x0` and omitting the `value` field of the `ref_record`.
856This serves as a tombstone, overriding any assertions about the
857existence of the reference from earlier files in the stack.
858
859### Compaction
860
861A partial stack of reftables can be compacted by merging references
862using a straightforward merge join across reftables, selecting the
863most recent value for output, and omitting deleted references that do
864not appear in remaining, lower reftables.
865
866A compacted reftable should set its `min_update_index` to the smallest of
867the input files' `min_update_index`, and its `max_update_index`
868likewise to the largest input `max_update_index`.
869
870For sake of illustration, assume the stack currently consists of
871reftable files (from oldest to newest): A, B, C, and D. The compactor
872is going to compact B and C, leaving A and D alone.
873
8741.  Obtain lock `tables.list.lock` and read the `tables.list` file.
8752.  Obtain locks `B.lock` and `C.lock`.
876    Ownership of these locks prevents other processes from trying
877    to compact these files.
8783.  Release `tables.list.lock`.
8794.  Compact `B` and `C` into a temp file `${min_update_index}-${max_update_index}_XXXXXX`.
8805.  Reacquire lock `tables.list.lock`.
8816.  Verify that `B` and `C` are still in the stack, in that order. This
882    should always be the case, assuming that other processes are adhering
883    to the locking protocol.
8847.  Rename `${min_update_index}-${max_update_index}_XXXXXX` to
885    `${min_update_index}-${max_update_index}.ref`.
8868.  Write the new stack to `tables.list.lock`, replacing `B` and `C` with the
887    file from (4).
8889.  Rename `tables.list.lock` to `tables.list`.
88910. Delete `B` and `C`, perhaps after a short sleep to avoid forcing
890    readers to backtrack.
891
892This strategy permits compactions to proceed independently of updates.
893
894Each reftable (compacted or not) is uniquely identified by its name, so open
895reftables can be cached by their name.
896
897## Alternatives considered
898
899### bzip packed-refs
900
901`bzip2` can significantly shrink a large packed-refs file (e.g. 62
902MiB compresses to 23 MiB, 37%).  However the bzip format does not support
903random access to a single reference. Readers must inflate and discard
904while performing a linear scan.
905
906Breaking packed-refs into chunks (individually compressing each chunk)
907would reduce the amount of data a reader must inflate, but still
908leaves the problem of indexing chunks to support readers efficiently
909locating the correct chunk.
910
911Given the compression achieved by reftable's encoding, it does not
912seem necessary to add the complexity of bzip/gzip/zlib.
913
914### Michael Haggerty's alternate format
915
916Michael Haggerty proposed [an alternate][mh-alt] format to reftable on
917the Git mailing list.  This format uses smaller chunks, without the
918restart table, and avoids block alignment with padding.  Reflog entries
919immediately follow each ref, and are thus interleaved between refs.
920
921Performance testing indicates reftable is faster for lookups (51%
922faster, 11.2 usec vs.  5.4 usec), although reftable produces a
923slightly larger file (+ ~3.2%, 28.3M vs 29.2M):
924
925format    |  size  | seek cold | seek hot  |
926---------:|-------:|----------:|----------:|
927mh-alt    | 28.3 M | 23.4 usec | 11.2 usec |
928reftable  | 29.2 M | 19.9 usec |  5.4 usec |
929
930[mh-alt]: https://public-inbox.org/git/CAMy9T_HCnyc1g8XWOOWhe7nN0aEFyyBskV2aOMb_fe+wGvEJ7A@mail.gmail.com/
931
932### JGit Ketch RefTree
933
934[JGit Ketch][ketch] proposed [RefTree][reftree], an encoding of
935references inside Git tree objects stored as part of the repository's
936object database.
937
938The RefTree format adds additional load on the object database storage
939layer (more loose objects, more objects in packs), and relies heavily
940on the packer's delta compression to save space.  Namespaces which are
941flat (e.g.  thousands of tags in refs/tags) initially create very
942large loose objects, and so RefTree does not address the problem of
943copying many references to modify a handful.
944
945Flat namespaces are not efficiently searchable in RefTree, as tree
946objects in canonical formatting cannot be binary searched. This fails
947the need to handle a large number of references in a single namespace,
948such as GitHub's `refs/pulls`, or a project with many tags.
949
950[ketch]: https://dev.eclipse.org/mhonarc/lists/jgit-dev/msg03073.html
951[reftree]: https://public-inbox.org/git/CAJo=hJvnAPNAdDcAAwAvU9C4RVeQdoS3Ev9WTguHx4fD0V_nOg@mail.gmail.com/
952
953### LMDB
954
955David Turner proposed [using LMDB][dt-lmdb], as LMDB is lightweight
956(64k of runtime code) and GPL-compatible license.
957
958A downside of LMDB is its reliance on a single C implementation.  This
959makes embedding inside JGit (a popular reimplemenation of Git)
960difficult, and hoisting onto virtual storage (for JGit DFS) virtually
961impossible.
962
963A common format that can be supported by all major Git implementations
964(git-core, JGit, libgit2) is strongly preferred.
965
966[dt-lmdb]: https://public-inbox.org/git/1455772670-21142-26-git-send-email-dturner@twopensource.com/
967
968## Future
969
970### Longer hashes
971
972Version will bump (e.g.  2) to indicate `value` uses a different
973object id length other than 20.  The length could be stored in an
974expanded file header, or hardcoded as part of the version.
975