{"thread":{"id":"46600","subject":"Re: reftable [v7]: new ref storage format","startedAt":"2017-08-16T02:49:25Z","lastAt":"2017-08-18T00:52:58Z","messageCount":7,"participants":["Shawn Pearce","Stefan Beller","Junio C Hamano","Michael Haggerty"],"isPatch":false,"patchVersion":null,"patchTotal":null},"messages":[{"id":"326485","messageId":"CAJo=hJsZcAM9sipdVr7TMD-FD2V2W6_pvMQ791EGCDsDkQ033w@mail.gmail.com","threadId":"46600","inReplyTo":null,"subject":"Re: reftable [v7]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-16T02:48:54Z","receivedAt":"2017-08-16T02:49:25Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"7th iteration of the reftable storage format.\n\nYou can read a rendered version of this here:\nhttps://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md\n\nChanges from v6:\n- Blocks are variable sized, and alignment is optional.\n- ref index is required on variable sized multi-block files.\n\n- restart_count/offsets are again at the end of the block.\n- value_type = 0x3 is only for symbolic references.\n- \"other\" files cannot be stored in reftable.\n\n- object blocks are explicitly optional.\n- object blocks use position (offset in bytes), not block id.\n- removed complex log_chained format for log blocks\n\n- Layout uses log, ref file extensions\n- Described reader algorithm to obtain a snapshot\n\n\n# reftable\n\n[TOC]\n\n## Overview\n\n### Problem statement\n\nSome repositories contain a lot of references (e.g.  android at 866k,\nrails at 31k).  The existing packed-refs format takes up a lot of\nspace (e.g.  62M), and does not scale with additional references.\nLookup of a single reference requires linearly scanning the file.\n\nAtomic pushes modifying multiple references require copying the\nentire packed-refs file, which can be a considerable amount of data\nmoved (e.g. 62M in, 62M out) for even small transactions (2 refs\nmodified).\n\nRepositories with many loose references occupy a large number of disk\nblocks from the local file system, as each reference is its own file\nstoring 41 bytes (and another file for the corresponding reflog).\nThis negatively affects the number of inodes available when a large\nnumber of repositories are stored on the same filesystem.  Readers can\nbe penalized due to the larger number of syscalls required to traverse\nand read the `$GIT_DIR/refs` directory.\n\n### Objectives\n\n- Near constant time lookup for any single reference, even when the\n  repository is cold and not in process or kernel cache.\n- Near constant time verification if a SHA-1 is referred to by at\n  least one reference (for allow-tip-sha1-in-want).\n- Efficient lookup of an entire namespace, such as `refs/tags/`.\n- Support atomic push with `O(size_of_update)` operations.\n- Combine reflog storage with ref storage for small transactions.\n- Separate reflog storage for base refs and historical logs.\n\n### Description\n\nA reftable file is a portable binary file format customized for\nreference storage. References are sorted, enabling linear scans,\nbinary search lookup, and range scans.\n\nStorage in the file is organized into variable sized blocks.  Prefix\ncompression is used within a single block to reduce disk space.  Block\nsize and alignment is tunable by the writer.\n\n### Performance\n\nSpace used, packed-refs vs. reftable:\n\nrepository | packed-refs | reftable | % original | avg ref  | avg obj\n-----------|------------:|---------:|-----------:|---------:|--------:\nandroid    |      62.2 M |   36.1 M |     58.0%  | 33 bytes | 5 bytes\nrails      |       1.8 M |    1.1 M |     57.7%  | 29 bytes | 4 bytes\ngit        |      78.7 K |   48.1 K |     61.0%  | 50 bytes | 4 bytes\ngit (heads)|       332 b |    269 b |     81.0%  | 33 bytes | 0 bytes\n\nScan (read 866k refs), by reference name lookup (single ref from 866k\nrefs), and by SHA-1 lookup (refs with that SHA-1, from 866k refs):\n\nformat      | cache | scan    | by name        | by SHA-1\n------------|------:|--------:|---------------:|---------------:\npacked-refs | cold  |  402 ms | 409,660.1 usec | 412,535.8 usec\npacked-refs | hot   |         |   6,844.6 usec |  20,110.1 usec\nreftable    | cold  |  112 ms |      33.9 usec |     323.2 usec\nreftable    | hot   |         |      20.2 usec |     320.8 usec\n\nSpace used for 149,932 log entries for 43,061 refs,\nreflog vs. reftable:\n\nformat        | size  | avg entry\n--------------|------:|-----------:\n$GIT_DIR/logs | 173 M | 1209 bytes\nreftable      |   5 M |   37 bytes\n\n## Details\n\n### Peeling\n\nReferences stored in a reftable are peeled, a record for an annotated\n(or signed) tag records both the tag object, and the object it refers\nto.\n\n### Reference name encoding\n\nReference names are an uninterpreted sequence of bytes that must pass\n[git-check-ref-format][ref-fmt] as a valid reference name.\n\n[ref-fmt]: https://git-scm.com/docs/git-check-ref-format\n\n### Network byte order\n\nAll multi-byte, fixed width fields are in network byte order.\n\n### Ordering\n\nBlocks are lexicographically ordered by their first reference.\n\n### Directory/file conflicts\n\nThe reftable format accepts both `refs/heads/foo` and\n`refs/heads/foo/bar` as distinct references.\n\nThis property is useful for retaining log records in reftable, but may\nconfuse versions of Git using `$GIT_DIR/refs` directory tree to\nmaintain references.  Users of reftable may choose to continue to\nreject `foo` and `foo/bar` type conflicts to prevent problems for\npeers.\n\n## File format\n\n### Structure\n\nA reftable file has the following high-level structure:\n\n    first_block {\n      header\n      first_ref_block\n    }\n    ref_block*\n    ref_index*\n    obj_block*\n    obj_index*\n    log_block*\n    log_index*\n    footer\n\nA log-only file omits the `ref_block`, `ref_index`, `obj_block` and\n`obj_index` sections, containing only the file header and log block:\n\n    first_block {\n      header\n    }\n    log_block*\n    log_index*\n    footer\n\nin a log-only file the first log block immediately follows the file\nheader, without padding to block alignment.\n\n### Block size\n\nThe file's block size is arbitrarily determined by the writer, and\ndoes not have to be a power of 2.  The block size must be larger than\nthe longest reference name or log entry used in the repository, as\nreferences cannot span blocks.\n\nPowers of two that are friendly to the virtual memory system or\nfilesystem (such as 4k or 8k) are recommended.  Larger sizes (64k) can\nyield better compression, with a possible increased cost incurred by\nreaders during access.\n\nThe largest block size is `16777215` bytes (15.99 MiB).\n\n### Block alignment\n\nWriters may choose to align blocks at multiples of the block size by\nincluding `padding` filled with NUL bytes at the end of a block to\nround out to the chosen alignment.  When alignment is used, writers\nmust specify the alignment with the file header's `block_size` field.\n\nBlock alignment is not required by the file format.  Unaligned files\nmust set `block_size = 0` in the file header, and omit `padding`.\nUnaligned files must include the [ref index](#Ref-index) to support\nfast lookup.  Readers must be able to read both aligned and\nnon-aligned files.\n\nVery small files (e.g. 1 only ref block) may omit `padding` and the\nref index to reduce total file size.\n\n### Header\n\nA 24-byte header appears at the beginning of the file:\n\n    'REFT'\n    uint8( version_number = 1 )\n    uint24( block_size )\n    uint64( min_update_index )\n    uint64( max_update_index )\n\nAligned files must specify `block_size` to configure readers with the\nexpected block alignment.  Unaligned files must set `block_size = 0`.\n\nThe `min_update_index` and `max_update_index` describe bounds for the\n`update_index` field of all log records in this file.  When reftables\nare used in a stack for [transactions](#Update-transactions), these\nfields can order the files such that the prior file's\n`max_update_index + 1` is the next file's `min_update_index`.\n\n### First ref block\n\nThe first ref block shares the same block as the file header, and is\n24 bytes smaller than all other blocks in the file.  The first block\nimmediately begins after the file header, at position 24.\n\nIf the first block is a log block (a log-only file), its block header\nbegins immediately at position 24.\n\n### Ref block format\n\nA ref block is written as:\n\n    'r'\n    uint24( block_len )\n    ref_record+\n    uint24( restart_offset )+\n    uint16( restart_count )\n\n    padding?\n\nBlocks begin with `block_type = 'r'` and a 3-byte `block_len` which\nencodes the number of bytes in the block up to, but not including the\noptional `padding`.  This is always less than or equal to the file's\nblock size.  In the first ref block, `block_len` includes 24 bytes\nfor the file header.\n\nThe 2-byte `restart_count` stores the number of entries in the\n`restart_offset` list, which must not be empty.  Readers can use\n`restart_count` to binary search between restarts before starting a\nlinear scan.\n\nExactly `restart_count` 3-byte `restart_offset` values precedes the\n`restart_count`.  Offsets are relative to the start of the block and\nrefer to the first byte of any `ref_record` whose name has not been\nprefix compressed.  Entries in the `restart_offset` list must be\nsorted, ascending.  Readers can start linear scans from any of these\nrecords.\n\nA variable number of `ref_record` fill the middle of the block,\ndescribing reference names and values.  The format is described below.\n\nAs the first ref block shares the first file block with the file\nheader, all `restart_offset` in the first block are relative to the\nstart of the file (position 0), and include the file header.  This\nforces the first `restart_offset` to be `28`.\n\n#### ref record\n\nA `ref_record` describes a single reference, storing both the name and\nits value(s). Records are formatted as:\n\n    varint( prefix_length )\n    varint( (suffix_length << 3) | value_type )\n    suffix\n    value?\n\nThe `prefix_length` field specifies how many leading bytes of the\nprior reference record's name should be copied to obtain this\nreference's name.  This must be 0 for the first reference in any\nblock, and also must be 0 for any `ref_record` whose offset is listed\nin the `restart_offset` table at the end of the block.\n\nRecovering a reference name from any `ref_record` is a simple concat:\n\n    this_name = prior_name[0..prefix_length] + suffix\n\nThe `suffix_length` value provides the number of bytes available in\n`suffix` to copy from `suffix` to complete the reference name.\n\nThe `value` follows.  Its format is determined by `value_type`, one of\nthe following:\n\n- `0x0`: deletion; no value data (see transactions, below)\n- `0x1`: one 20-byte object id; value of the ref\n- `0x2`: two 20-byte object ids; value of the ref, peeled target\n- `0x3`: symbolic reference: `varint( target_len ) target`\n\nSymbolic references use `0x3`, followed by the complete name of the\nreference target.  No compression is applied to the target name.\n\nTypes `0x4..0x7` are reserved for future use.\n\n### Ref index\n\nThe ref index stores the name of the last reference from every ref\nblock in the file, enabling reduced disk seeks for lookups.  Any\nreference can be found by searching the index, identifying the\ncontaining block, and searching within that block.\n\nThe index may be organized into a multi-level index, where the 1st\nlevel index block points to additional ref index blocks (2nd level),\nwhich may in turn point to either additional index blocks (e.g. 3rd\nlevel) or ref blocks (leaf level).  Disk reads required to access a\nref go up with higher index levels.  Multi-level indexes may be\nrequired to ensure no single index block exceeds the file format's max\nblock size of `16777215` bytes (15.99 MiB).  To acheive constant O(1)\ndisk seeks for lookups the index must be a single level, which is\npermitted to exceed the file's configured block size, but not the\nformat's max block size of 15.99 MiB.\n\nIf present, the ref index block(s) appears after the last ref block.\n\nIf there are at least 4 ref blocks, a ref index block should be\nwritten to improve lookup times.  Cold reads using the index require\n2 disk reads (read index, read block), and binary searching < 4 blocks\nalso requires <= 2 reads.  Omitting the index block from smaller files\nsaves space.\n\nIf the file is unaligned and contains more than one ref block, the ref\nindex must be written.\n\nIndex block format:\n\n    'i'\n    uint24( block_len )\n    index_record+\n    uint24( restart_offset )+\n    uint16( restart_count )\n\n    padding?\n\nThe index blocks begin with `block_type = 'i'` and a 3-byte\n`block_len` which encodes the number of bytes in the block,\nup to but not including the optional `padding`.\n\nThe `restart_offset` and `restart_count` fields are identical in\nformat, meaning and usage as in ref blocks.\n\nTo reduce the number of reads required for random access in very large\nfiles the index block may be larger than other blocks.  However,\nreaders must hold the entire index in memory to benefit from this, so\nit's a time-space tradeoff in both file size and reader memory.\n\nIncreasing the file's block size decreases the index size.\nAlternatively a multi-level index may be used, keeping index blocks\nwithin the file's block size, but increasing the number of blocks\nthat need to be accessed.\n\n#### index record\n\nAn index record describes the last entry in another block.\nIndex records are written as:\n\n    varint( prefix_length )\n    varint( (suffix_length << 3) | 0 )\n    suffix\n    varint( block_position )\n\nIndex records use prefix compression exactly like `ref_record`.\n\nIndex records store `block_position` after the suffix, specifying the\nabsolute position in bytes (from the start of the file) of the block\nthat ends with this reference. Readers can seek to `block_position` to\nbegin reading the block header.\n\nReaders must examine the block header at `block_position` to determine\nif the next block is another level index block, or the leaf-level ref\nblock.\n\n#### Reading the index\n\nReaders loading the ref index must first read the footer (below) to\nobtain `ref_index_position`. If not present, the position will be 0.\nThe `ref_index_position` is for the 1st level root of the ref index.\n\n### Obj block format\n\nObject blocks are optional.  Writers may choose to omit object blocks,\nespecially if readers will not use the SHA-1 to ref mapping.\n\nObject blocks use unique, abbreviated 2-20 byte SHA-1 keys, mapping\nto ref blocks containing references pointing to that object directly,\nor as the peeled value of an annotated tag.  Like ref blocks, object\nblocks use the file's standard block size. The abbrevation length is\navailable in the footer as `obj_id_len`.\n\nTo save space in small files, object blocks may be omitted if the ref\nindex is not present, as brute force search will only need to read a\nfew ref blocks.  When missing, readers should brute force a linear\nsearch of all references to lookup by SHA-1.\n\nAn object block is written as:\n\n    'o'\n    uint24( block_len )\n    obj_record+\n    uint24( restart_offset )+\n    uint16( restart_count )\n\n    padding?\n\nFields are identical to ref block.  Binary search using the restart\ntable works the same as in reference blocks.\n\nBecause object identifiers are abbreviated by writers to the shortest\nunique abbreviation within the reftable, obj key lengths are variable\nbetween 2 and 20 bytes.  Readers must compare only for common prefix\nmatch within an obj block or obj index.\n\n#### obj record\n\nAn `obj_record` describes a single object abbreviation, and the blocks\ncontaining references using that unique abbreviation:\n\n    varint( prefix_length )\n    varint( (suffix_length << 3) | cnt_3 )\n    suffix\n    varint( cnt_large )?\n    varint( position_delta )*\n\nLike in reference blocks, abbreviations are prefix compressed within\nan obj block.  On large reftables with many unique objects, higher\nblock sizes (64k), and higher restart interval (128), a\n`prefix_length` of 2 or 3 and `suffix_length` of 3 may be common in\nobj records (unique abbreviation of 5-6 raw bytes, 10-12 hex digits).\n\nEach record contains `position_count` number of positions for matching\nref blocks.  For 1-7 positions the count is stored in `cnt_3`.  When\n`cnt_3 = 0` the actual count follows in a varint, `cnt_large`.\n\nThe use of `cnt_3` bets most objects are pointed to by only a single\nreference, some may be pointed to by a couple of references, and very\nfew (if any) are pointed to by more than 7 references.\n\nA special case exists when `cnt_3 = 0` and `cnt_large = 0`: there\nare no `position_delta`, but at least one reference starts with this\nabbreviation.  A reader that needs exact reference names must scan all\nreferences to find which specific references have the desired object.\nWriters should use this format when the `position_delta` list would have\noverflowed the file's block size due to a high number of references\npointing to the same object.\n\nThe first `position_delta` is the position from the start of the file.\nAdditional `position_delta` entries are sorted ascending and relative\nto the prior entry, e.g.  a reader would perform:\n\n    pos = position_delta[0]\n    prior = pos\n    for (j = 1; j < position_count; j++) {\n      pos = prior + position_delta[j]\n      prior = pos\n    }\n\nWith a position in hand, a reader must linearly scan the ref block,\nstarting from the first `ref_record`, testing each reference's SHA-1s\n(for `value_type = 0x1` or `0x2`) for full equality.  Faster searching\nby SHA-1 within a single ref block is not supported by the reftable\nformat.  Smaller block sizes reduce the number of candidates this step\nmust consider.\n\n### Obj index\n\nThe obj index stores the abbreviation from the last entry for every\nobj block in the file, enabling reduced disk seeks for all lookups.\nIt is formatted exactly the same as the ref index, but refers to obj\nblocks.\n\nThe obj index should be present if obj blocks are present, as\nobj blocks should only be written in larger files.\n\nReaders loading the obj index must first read the footer (below) to\nobtain `obj_index_position`.  If not present, the position will be 0.\n\n### Log block format\n\nUnlike ref and obj blocks, log blocks are always unaligned.\n\nLog blocks are variable in size, and do not match the `block_size`\nspecified in the file header or footer.  Writers should choose an\nappropriate buffer size to prepare a log block for deflation, such as\n`2 * block_size`.\n\nA log block is written as:\n\n    'g'\n    uint24( block_len )\n    zlib_deflate {\n      log_record+\n      uint24( restart_offset )+\n      uint16( restart_count )\n    }\n\nLog blocks look similar to ref blocks, except `block_type = 'g'`.\n\nThe 4-byte block header is followed by the deflated block contents\nusing zlib deflate.  The `block_len` in the header is the inflated\nsize (including 4-byte block header), and should be used by readers to\npreallocate the inflation output buffer.  A log block's `block_len`\nmay exceed the file's block size.\n\nOffsets within the log block (e.g.  `restart_offset`) still include\nthe 4-byte header.  Readers may prefer prefixing the inflation output\nbuffer with the 4-byte header.\n\nWithin the deflate container, a variable number of `log_record`\ndescribe reference changes.  The log record format is described\nbelow.  See ref block format (above) for a description of\n`restart_offset` and `restart_count`.\n\nBecause log blocks have no alignment or padding between blocks,\nreaders must keep track of the bytes consumed by the inflater to\nknow where the next log block begins.\n\n#### log record\n\nLog record keys are structured as:\n\n    ref_name '\\0' reverse_int64( update_index )\n\nwhere `update_index` is the unique transaction identifier.  The\n`update_index` field must be unique within the scope of a `ref_name`.\nSee the update transactions section below for further details.\n\nThe `reverse_int64` function inverses the value so lexographical\nordering the network byte order encoding sorts the more recent records\nwith higher `update_index` values first:\n\n    reverse_int64(int64 t) {\n      return 0xffffffffffffffff - t;\n    }\n\nLog records have a similar starting structure to ref and index\nrecords, utilizing the same prefix compression scheme applied to the\nlog record key described above.\n\n```\n    varint( prefix_length )\n    varint( (suffix_length << 3) | log_type )\n    suffix\n    log_data {\n      old_id\n      new_id\n      varint( name_length    )  name\n      varint( email_length   )  email\n      varint( time_seconds )\n      sint16( tz_offset )\n      varint( message_length )  message\n    }?\n```\n\nLog record entries use `log_type` to indicate what follows:\n\n- `0x0`: deletion; no log data.\n- `0x1`: standard git reflog data using `log_data` above.\n\nThe `log_type = 0x0` is mostly useful for `git stash drop`, removing\nan entry from the reflog of `refs/stash` in a transaction file\n(below), without needing to rewrite larger files.  Readers reading a\nstack of reflogs must treat this as a deletion.\n\nFor `log_type = 0x1`, the `log_data` section follows\n[git update-ref][update-ref] logging, and includes:\n\n- two 20-byte SHA-1s (old id, new id)\n- varint string of committer's name\n- varint string of committer's email\n- varint time in seconds since epoch (Jan 1, 1970)\n- 2-byte timezone offset in minutes (signed)\n- varint string of message\n\n`tz_offset` is the absolute number of minutes from GMT the committer\nwas at the time of the update.  For example `GMT-0800` is encoded in\nreftable as `sint16(-480)` and `GMT+0230` is `sint16(150)`.\n\nThe committer email does not contain `<` or `>`, it's the value\nnormally found between the `<>` in a git commit object header.\n\nThe `message_length` may be 0, in which case there was no message\nsupplied for the update.\n\n[update-ref]: https://git-scm.com/docs/git-update-ref#_logging_updates\n\n#### Reading the log\n\nReaders accessing the log must first read the footer (below) to\ndetermine the `log_position`.  The first block of the log begins at\n`log_position` bytes since the start of the file.  The `log_position`\nis not block aligned.\n\n#### Importing logs\n\nWhen importing from `$GIT_DIR/logs` writers should globally order all\nlog records roughly by timestamp while preserving file order, and\nassign unique, increasing `update_index` values for each log line.\nNewer log records get higher `update_index` values.\n\nAlthough an import may write only a single reftable file, the reftable\nfile must span many unique `update_index`, as each log line requires\nits own `update_index` to preserve semantics.\n\n### Log index\n\nThe log index stores the log key (`refname \\0 reverse_int64(update_index)`)\nfor the last log record of every log block in the file, supporting\nbounded-time lookup.\n\nA log index block must be written if 2 or more log blocks are written\nto the file.  If present, the log index appears after the last log\nblock.  There is no padding used to align the log index to block\nalignment.\n\nLog index format is identical to ref index, except the keys are 9\nbytes longer to include `'\\0'` and the 8-byte\n`reverse_int64(update_index)`.  Records use `block_position` to\nrefer to the start of a log block.\n\n#### Reading the index\n\nReaders loading the log index must first read the footer (below) to\nobtain `log_index_position`. If not present, the position will be 0.\n\n### Footer\n\nAfter the last block of the file, a file footer is written.  It begins\nlike the file header, but is extended with additional data.\n\nA 68-byte footer appears at the end:\n\n```\n    'REFT'\n    uint8( version_number = 1 )\n    uint24( block_size )\n    uint64( min_update_index )\n    uint64( max_update_index )\n\n    uint64( ref_index_position )\n    uint64( (obj_position << 5) | obj_id_len )\n    uint64( obj_index_position )\n\n    uint64( log_position )\n    uint64( log_index_position )\n\n    uint32( CRC-32 of above )\n```\n\nIf a section is missing (e.g. ref index) the corresponding position\nfield (e.g. `ref_index_position`) will be 0.\n\n- `obj_position`: byte position for the first obj block.\n- `obj_id_len`: number of bytes used to abbreviate object identifiers\n  in obj blocks.\n- `log_position`: byte position for the first log block.\n- `ref_index_position`: byte position for the start of the ref index.\n- `obj_index_position`: byte position for the start of the obj index.\n- `log_index_position`: byte position for the start of the log index.\n\n#### Reading the footer\n\nReaders must seek to `file_length - 68` to access the footer.  A\ntrusted external source (such as `stat(2)`) is necessary to obtain\n`file_length`.  When reading the footer, readers must verify:\n\n- 4-byte magic is correct\n- 1-byte version number is recognized\n- 4-byte CRC-32 matches the other 64 bytes (including magic, and version)\n\nOnce verified, the other fields of the footer can be accessed.\n\n### Varint encoding\n\nVarint encoding is identical to the ofs-delta encoding method used\nwithin pack files.\n\nDecoder works such as:\n\n    val = buf[ptr] & 0x7f\n    while (buf[ptr] & 0x80) {\n      ptr++\n      val = ((val + 1) << 7) | (buf[ptr] & 0x7f)\n    }\n\n### Binary search\n\nBinary search within a block is supported by the `restart_offset`\nfields at the end of the block.  Readers can binary search through the\nrestart table to locate between which two restart points the sought\nreference or key should appear.\n\nEach record identified by a `restart_offset` stores the complete key\nin the `suffix` field of the record, making the compare operation\nduring binary search straightforward.\n\nOnce a restart point lexicographically before the sought reference has\nbeen identified, readers can linearly scan through the following\nrecord entries to locate the sought record, terminating if the current\nrecord sorts after (and therefore the sought key is not present).\n\n#### Restart point selection\n\nWriters determine the restart points at file creation.  The process is\narbitrary, but every 16 or 64 records is recommended.  Every 16 may\nbe more suitable for smaller block sizes (4k or 8k), every 64 for\nlarger block sizes (64k).\n\nMore frequent restart points reduces prefix compression and increases\nspace consumed by the restart table, both of which increase file size.\n\nLess frequent restart points makes prefix compression more effective,\ndecreasing overall file size, with increased penalities for readers\nwalking through more records after the binary search step.\n\nA maximum of `65535` restart points per block is supported.\n\n## Considerations\n\n### Lightweight refs dominate\n\nThe reftable format assumes the vast majority of references are single\nSHA-1 valued with common prefixes, such as Gerrit Code Review's\n`refs/changes/` namespace, GitHub's `refs/pulls/` namespace, or many\nlightweight tags in the `refs/tags/` namespace.\n\nAnnotated tags storing the peeled object cost an additional 20 bytes\nper reference.\n\n### Low overhead\n\nA reftable with very few references (e.g. git.git with 5 heads)\nis 269 bytes for reftable, vs. 332 bytes for packed-refs.  This\nsupports reftable scaling down for transaction logs (below).\n\n### Block size\n\nFor a Gerrit Code Review type repository with many change refs, larger\nblock sizes (64 KiB) and less frequent restart points (every 64) yield\nbetter compression due to more references within the block compressing\nagainst the prior reference.\n\nLarger block sizes reduce the index size, as the reftable will\nrequire fewer blocks to store the same number of references.\n\n### Minimal disk seeks\n\nAssuming the index block has been loaded into memory, binary searching\nfor any single reference requires exactly 1 disk seek to load the\ncontaining block.\n\n### Scans and lookups dominate\n\nScanning all references and lookup by name (or namespace such as\n`refs/heads/`) are the most common activities performed on repositories.\nSHA-1s are stored directly with references to optimize this use case.\n\n### Logs are infrequently read\n\nLogs are infrequently accessed, but can be large.  Deflating log\nblocks saves disk space, with some increased penalty at read time.\n\nLogs are stored in an isolated section from refs, reducing the burden\non reference readers that want to ignore logs.  Further, historical\nlogs can be isolated into log-only files.\n\n### Logs are read backwards\n\nLogs are frequently accessed backwards (most recent N records for\nmaster to answer `master@{4}`), so log records are grouped by\nreference, and sorted descending by update index.\n\n## Repository format\n\n### Version 1\n\nA repository must set its `$GIT_DIR/config` to configure reftable:\n\n    [core]\n        repositoryformatversion = 1\n    [extensions]\n        refStorage = reftable\n\n### Layout\n\nThe `$GIT_DIR/refs` path is a file when reftable is configured, not a\ndirectory.  This prevents loose references from being stored.\n\nA collection of reftable files are stored in the `$GIT_DIR/reftable/`\ndirectory:\n\n    00000001.log\n    00000001.ref\n    00000002.ref\n\nwhere reftable files are named by a unique name such as produced by\nthe function `${update_index}.ref`.\n\nThe stack ordering file is `$GIT_DIR/refs` and lists the current\nfiles, one per line, in order, from oldest (base) to newest (most\nrecent):\n\n    $ cat .git/refs\n    00000001.log\n    00000001.ref\n    00000002.ref\n\nReaders must read `$GIT_DIR/refs` to determine which files are\nrelevant right now, and search through the stack in reverse order\n(last reftable is examined first).\n\nReftable files not listed in `refs` may be new (and about to be added\nto the stack by the active writer), or ancient and ready to be pruned.\n\n### Readers\n\nReaders can obtain a consistent snapshot of the reference space by\nfollowing:\n\n1.  Open and read the `refs` file.\n2.  Open each of the reftable files that it mentions.\n3.  If any of the files is missing, goto 1.\n4.  Read from the now-open files as long as necessary.\n\n### Update transactions\n\nAlthough reftables are immutable, mutations are supported by writing a\nnew reftable and atomically appending it to the stack:\n\n1. Acquire `refs.lock`.\n2. Read `refs` to determine current reftables.\n3. Select `update_index` to be most recent file's `max_update_index + 1`.\n4. Prepare temp reftable `${update_index}_XXXXXX`, including log entries.\n5. Rename `${update_index}_XXXXXX` to `${update_index}.ref`.\n6. Copy `refs` to `refs.lock`, appending file from (5).\n7. Rename `refs.lock` to `refs`.\n\nDuring step 4 the new file's `min_update_index` and `max_update_index`\nare both set to the `update_index` selected by step 3.  All log\nrecords for the transaction use the same `update_index` in their keys.\nThis enables later correlation of which references were updated by the\nsame transaction.\n\nBecause a single `refs.lock` file is used to manage locking, the\nrepository is single-threaded for writers.  Writers may have to\nbusy-spin (with backoff) around creating `refs.lock`, for up to an\nacceptable wait period, aborting if the repository is too busy to\nmutate.  Application servers wrapped around repositories (e.g.  Gerrit\nCode Review) can layer their own lock/wait queue to improve fairness\nto writers.\n\n### Reference deletions\n\nDeletion of any reference can be explicitly stored by setting the\n`type` to `0x0` and omitting the `value` field of the `ref_record`.\nThis serves as a tombstone, overriding any assertions about the\nexistence of the reference from earlier files in the stack.\n\n### Compaction\n\nA partial stack of reftables can be compacted by merging references\nusing a straightforward merge join across reftables, selecting the\nmost recent value for output, and omitting deleted references that do\nnot appear in remaining, lower reftables.\n\nA compacted reftable should set its `min_update_index` to the smallest of\nthe input files' `min_update_index`, and its `max_update_index`\nlikewise to the largest input `max_update_index`.\n\nFor sake of illustration, assume the stack currently consists of\nreftable files (from oldest to newest): A, B, C, and D. The compactor\nis going to compact B and C, leaving A and D alone.\n\n1.  Obtain lock `refs.lock` and read the `refs` file.\n2.  Obtain locks `B.lock` and `C.lock`.\n    Ownership of these locks prevents other processes from trying\n    to compact these files.\n3.  Release `refs.lock`.\n4.  Compact `B` and `C` into a temp file `${min_update_index}_XXXXXX`.\n5.  Reacquire lock `refs.lock`.\n6.  Verify that `B` and `C` are still in the stack, in that order. This\n    should always be the case, assuming that other processes are adhering\n    to the locking protocol.\n7.  Rename `${min_update_index}_XXXXXX` to `${min_update_index}.ref`.\n8.  Write the new stack to `refs.lock`, replacing `B` and `C` with the\n    file from (4).\n9.  Rename `refs.lock` to `refs`.\n10. Delete `B` and `C`, perhaps after a short sleep to avoid forcing\n    readers to backtrack.\n\nThis strategy permits compactions to proceed independently of updates.\n\n## Alternatives considered\n\n### bzip packed-refs\n\n`bzip2` can significantly shrink a large packed-refs file (e.g. 62\nMiB compresses to 23 MiB, 37%).  However the bzip format does not support\nrandom access to a single reference. Readers must inflate and discard\nwhile performing a linear scan.\n\nBreaking packed-refs into chunks (individually compressing each chunk)\nwould reduce the amount of data a reader must inflate, but still\nleaves the problem of indexing chunks to support readers efficiently\nlocating the correct chunk.\n\nGiven the compression achieved by reftable's encoding, it does not\nseem necessary to add the complexity of bzip/gzip/zlib.\n\n### Michael Haggerty's alternate format\n\nMichael Haggerty proposed [an alternate][mh-alt] format to reftable on\nthe Git mailing list.  This format uses smaller chunks, without the\nrestart table, and avoids block alignment with padding.  Reflog entries\nimmediately follow each ref, and are thus interleaved between refs.\n\nPerformance testing indicates reftable is faster for lookups (51%\nfaster, 11.2 usec vs.  5.4 usec), although reftable produces a\nslightly larger file (+ ~3.2%, 28.3M vs 29.2M):\n\nformat    |  size  | seek cold | seek hot  |\n---------:|-------:|----------:|----------:|\nmh-alt    | 28.3 M | 23.4 usec | 11.2 usec |\nreftable  | 29.2 M | 19.9 usec |  5.4 usec |\n\n[mh-alt]: https://public-inbox.org/git/CAMy9T_HCnyc1g8XWOOWhe7nN0aEFyyBskV2aOMb_fe+wGvEJ7A@mail.gmail.com/\n\n### JGit Ketch RefTree\n\n[JGit Ketch][ketch] proposed [RefTree][reftree], an encoding of\nreferences inside Git tree objects stored as part of the repository's\nobject database.\n\nThe RefTree format adds additional load on the object database storage\nlayer (more loose objects, more objects in packs), and relies heavily\non the packer's delta compression to save space.  Namespaces which are\nflat (e.g.  thousands of tags in refs/tags) initially create very\nlarge loose objects, and so RefTree does not address the problem of\ncopying many references to modify a handful.\n\nFlat namespaces are not efficiently searchable in RefTree, as tree\nobjects in canonical formatting cannot be binary searched. This fails\nthe need to handle a large number of references in a single namespace,\nsuch as GitHub's `refs/pulls`, or a project with many tags.\n\n[ketch]: https://dev.eclipse.org/mhonarc/lists/jgit-dev/msg03073.html\n[reftree]: https://public-inbox.org/git/CAJo=hJvnAPNAdDcAAwAvU9C4RVeQdoS3Ev9WTguHx4fD0V_nOg@mail.gmail.com/\n\n### LMDB\n\nDavid Turner proposed [using LMDB][dt-lmdb], as LMDB is lightweight\n(64k of runtime code) and GPL-compatible license.\n\nA downside of LMDB is its reliance on a single C implementation.  This\nmakes embedding inside JGit (a popular reimplemenation of Git)\ndifficult, and hoisting onto virtual storage (for JGit DFS) virtually\nimpossible.\n\nA common format that can be supported by all major Git implementations\n(git-core, JGit, libgit2) is strongly preferred.\n\n[dt-lmdb]: https://public-inbox.org/git/1455772670-21142-26-git-send-email-dturner@twopensource.com/\n\n## Future\n\n### Longer hashes\n\nVersion will bump (e.g.  2) to indicate `value` uses a different\nobject id length other than 20.  The length could be stored in an\nexpanded file header, or hardcoded as part of the version.\n"},{"id":"326489","messageId":"CAGZ79kZ4m0-KBFs1pbOvRqkR=0vn-Jbn1FATL_KzW+km0K-S2A@mail.gmail.com","threadId":"46600","inReplyTo":"CAJo=hJsZcAM9sipdVr7TMD-FD2V2W6_pvMQ791EGCDsDkQ033w@mail.gmail.com","subject":"Re: reftable [v7]: new ref storage format","fromName":"Stefan Beller","fromEmail":"sbeller@google.com","sentAt":"2017-08-16T06:15:45Z","receivedAt":"2017-08-16T06:15:52Z","isPatch":false,"sender":{"key":"stefanbeller@gmail.com","avatar":"https://avatars.githubusercontent.com/u/455868?v=4"},"body":"On Tue, Aug 15, 2017 at 7:48 PM, Shawn Pearce <spearce@spearce.org> wrote:\n> 7th iteration of the reftable storage format.\n>\n> You can read a rendered version of this here:\n> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md\n>\n> Changes from v6:\n> - Blocks are variable sized, and alignment is optional.\n> - ref index is required on variable sized multi-block files.\n>\n> - restart_count/offsets are again at the end of the block.\n> - value_type = 0x3 is only for symbolic references.\n> - \"other\" files cannot be stored in reftable.\n>\n> - object blocks are explicitly optional.\n> - object blocks use position (offset in bytes), not block id.\n> - removed complex log_chained format for log blocks\n>\n> - Layout uses log, ref file extensions\n> - Described reader algorithm to obtain a snapshot\n\n- back to the old \"intra-block index is last\"\n  for all block types. ok.\n- changed (only ref?) indexes to start char + 3 byte size:\n  Which starting char do object/log indexes have?\n\n\"Unaligned files must include the ref index to support fast lookup.\"\n\nWhy this? I would imagine the client (which has ~5 branches),\nwould not need this, but only a ref block, that's it.\n\nCtrl-F for 'block_size' reveals nothing is computed\nrelative to the block_size in this format, yet we can\nset it to an arbitrary number. If following the spec,\nthe reader at $DAY_JOB needs to be able to read\nboth aligned and unaligned reftables, despite our plan\nto ever write aligned ref tables, what would the reader\nuse the block_size for? (I think we can omit that field\nfrom the header/footer now, no?)\n"},{"id":"326509","messageId":"CAJo=hJtAL9SX5Z4XyNFS5L+H3j3OaTe6t-ug7oefpNMXHh525A@mail.gmail.com","threadId":"46600","inReplyTo":"CAGZ79kZ4m0-KBFs1pbOvRqkR=0vn-Jbn1FATL_KzW+km0K-S2A@mail.gmail.com","subject":"Re: reftable [v7]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-16T15:54:10Z","receivedAt":"2017-08-16T15:54:36Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Tue, Aug 15, 2017 at 11:15 PM, Stefan Beller <sbeller@google.com> wrote:\n> On Tue, Aug 15, 2017 at 7:48 PM, Shawn Pearce <spearce@spearce.org> wrote:\n>> 7th iteration of the reftable storage format.\n>>\n>> You can read a rendered version of this here:\n>> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md\n>>\n>> Changes from v6:\n>> - Blocks are variable sized, and alignment is optional.\n>> - ref index is required on variable sized multi-block files.\n>>\n>> - restart_count/offsets are again at the end of the block.\n>> - value_type = 0x3 is only for symbolic references.\n>> - \"other\" files cannot be stored in reftable.\n>>\n>> - object blocks are explicitly optional.\n>> - object blocks use position (offset in bytes), not block id.\n>> - removed complex log_chained format for log blocks\n>>\n>> - Layout uses log, ref file extensions\n>> - Described reader algorithm to obtain a snapshot\n>\n> - back to the old \"intra-block index is last\"\n>   for all block types. ok.\n\nYes, it simplifies \"streaming writers\" who don't want to buffer a lot.\n\n> - changed (only ref?) indexes to start char + 3 byte size:\n>   Which starting char do object/log indexes have?\n\nAll index blocks use 'i'.\n\n> \"Unaligned files must include the ref index to support fast lookup.\"\n>\n> Why this? I would imagine the client (which has ~5 branches),\n> would not need this, but only a ref block, that's it.\n\nThe quoted part is I think incomplete. Unaligned files need the ref\nindex if there is more than one ref block, as there is no way to\ndivide the space for binary search. A single ref block with 5 branches\ndoes not need the ref index.\n\n> Ctrl-F for 'block_size' reveals nothing is computed\n> relative to the block_size in this format, yet we can\n> set it to an arbitrary number. If following the spec,\n> the reader at $DAY_JOB needs to be able to read\n> both aligned and unaligned reftables, despite our plan\n> to ever write aligned ref tables, what would the reader\n> use the block_size for? (I think we can omit that field\n> from the header/footer now, no?)\n\nIts really helpful to be present for the reader to know how to locate\nand read blocks. If the ref index is missing and there are multiple\nref blocks in an aligned file, a reader can use block_size to divide\nthe space and perform binary search. Even when the ref index is\npresent, the reader can use block_size to issue a disk IO read of\nblock_size bytes without reading the block_len of the target block\nfirst.\n\nAt $DAY_JOB the block_size is tunable by the writer and could change\nat any time, so its useful to have it embedded in the output.\n"},{"id":"326558","messageId":"xmqq60dnjka0.fsf@gitster.mtv.corp.google.com","threadId":"46600","inReplyTo":"CAJo=hJsZcAM9sipdVr7TMD-FD2V2W6_pvMQ791EGCDsDkQ033w@mail.gmail.com","subject":"Re: reftable [v7]: new ref storage format","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2017-08-16T21:05:27Z","receivedAt":"2017-08-16T21:05:35Z","isPatch":false,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Shawn Pearce <spearce@spearce.org> writes:\n\n> 7th iteration of the reftable storage format.\n>\n> You can read a rendered version of this here:\n> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md\n>\n> Changes from v6:\n> - Blocks are variable sized, and alignment is optional.\n> - ref index is required on variable sized multi-block files.\n>\n> - restart_count/offsets are again at the end of the block.\n> - value_type = 0x3 is only for symbolic references.\n> - \"other\" files cannot be stored in reftable.\n>\n> - object blocks are explicitly optional.\n> - object blocks use position (offset in bytes), not block id.\n> - removed complex log_chained format for log blocks\n>\n> - Layout uses log, ref file extensions\n> - Described reader algorithm to obtain a snapshot\n\nI read this version through pretending that I never read the\nprevious iterations, and it still made sense to me, which is a good\nindication that the document is well self contained.  \n\nI think I agree with all the simplication from v6.\n\nI found it a slightly odd that we do not insist that update_indices\nthat appear in a single reftable file are consecutive, yet we\nrequire that min_update_index of a reftable file must be one greater\nthan the max_update_index of a previous one.  That is not a new\nissue in v7, though.\n\nThanks.\n"},{"id":"326587","messageId":"CAMy9T_GuU68mQTAvmPkaa6jPiNnoDAKCqA8y76rf3UrmMeyfTA@mail.gmail.com","threadId":"46600","inReplyTo":"xmqq60dnjka0.fsf@gitster.mtv.corp.google.com","subject":"Re: reftable [v7]: new ref storage format","fromName":"Michael Haggerty","fromEmail":"mhagger@alum.mit.edu","sentAt":"2017-08-17T08:06:54Z","receivedAt":"2017-08-17T08:07:10Z","isPatch":false,"sender":{"key":"mhagger@alum.mit.edu","avatar":"https://avatars.githubusercontent.com/u/119718?v=4"},"body":"On Wed, Aug 16, 2017 at 11:05 PM, Junio C Hamano <gitster@pobox.com> wrote:\n> I found it a slightly odd that we do not insist that update_indices\n> that appear in a single reftable file are consecutive, yet we\n> require that min_update_index of a reftable file must be one greater\n> than the max_update_index of a previous one.  That is not a new\n> issue in v7, though.\n\nI think of `update_index` like a pseudo-time, and the\n`min_update_index` and `max_update_index` to be stating that \"this\nreftable covers the time interval specified\". So it's reasonable to\nsay that the reftable files, together, should cover all time.\n\nBut it might be that there are values of `update_index` for which no\nevents survived within a reftable file that covers that time interval.\nThis can happen if reference update records have been compacted away\nbecause later reference updates overwrote their effects, and either\n\n* reflogs were turned off for those updates, or\n* the corresponding reflogs have been compacted into a separate file, or\n* the corresponding reflog entries for those updates have been expired.\n\nMichael\n"},{"id":"326624","messageId":"xmqqefsagikx.fsf@gitster.mtv.corp.google.com","threadId":"46600","inReplyTo":"CAMy9T_GuU68mQTAvmPkaa6jPiNnoDAKCqA8y76rf3UrmMeyfTA@mail.gmail.com","subject":"Re: reftable [v7]: new ref storage format","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2017-08-17T18:22:38Z","receivedAt":"2017-08-17T18:22:46Z","isPatch":false,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"Michael Haggerty <mhagger@alum.mit.edu> writes:\n\n> On Wed, Aug 16, 2017 at 11:05 PM, Junio C Hamano <gitster@pobox.com> wrote:\n>> I found it a slightly odd that we do not insist that update_indices\n>> that appear in a single reftable file are consecutive, yet we\n>> require that min_update_index of a reftable file must be one greater\n>> than the max_update_index of a previous one.  That is not a new\n>> issue in v7, though.\n>\n> I think of `update_index` like a pseudo-time, and the\n> `min_update_index` and `max_update_index` to be stating that \"this\n> reftable covers the time interval specified\". So it's reasonable to\n> say that the reftable files, together, should cover all time.\n>\n> But it might be that there are values of `update_index` for which no\n> events survived within a reftable file that covers that time interval.\n> This can happen if reference update records have been compacted away\n> because later reference updates overwrote their effects, and either\n>\n> * reflogs were turned off for those updates, or\n> * the corresponding reflogs have been compacted into a separate file, or\n> * the corresponding reflog entries for those updates have been expired.\n\nYeah, and I think it is reasonable that the specification does not\ndictate that indices within a single reftable must be consecutive.\n\nAnd if update_indices within a single reftable are allowed to be\nsparse, e.g. recording three transactions with indices 1 3 and 5, it\nis not immediately obvious to me why the transactions that are\nrecorded in the next reftable cannot be with indices 7 8 and 10,\nleaving a gap between the max in the first table (i.e. 5) and the\nmin in the second table (i.e. 7).  That is what I found slightly\nodd.\n\n\n\n"},{"id":"326659","messageId":"CAJo=hJtQa5Yo8Fcy4Yn1tFLG6Ydy846J5pzLt8sF0y_1GGb32g@mail.gmail.com","threadId":"46600","inReplyTo":"CAJo=hJsZcAM9sipdVr7TMD-FD2V2W6_pvMQ791EGCDsDkQ033w@mail.gmail.com","subject":"Re: reftable [v7]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-18T00:52:31Z","receivedAt":"2017-08-18T00:52:58Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Tue, Aug 15, 2017 at 7:48 PM, Shawn Pearce <spearce@spearce.org> wrote:\n> 7th iteration of the reftable storage format.\n>\n> You can read a rendered version of this here:\n> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md\n\nFYI, JGit has adopted this v7 draft as version 1 of the reftable\nformat. The file reader/writer implementations will be in the next\nversion of JGit. Transaction support in the $GIT_DIR layout still\nneeds to be implemented.\n"}]}