{"thread":{"id":"46523","subject":"Re: reftable [v6]: new ref storage format","startedAt":"2017-08-07T01:47:36Z","lastAt":"2017-08-14T12:13:36Z","messageCount":12,"participants":["Shawn Pearce","Stefan Beller","Jeff King","Junio C Hamano","Michael Haggerty"],"isPatch":false,"patchVersion":null,"patchTotal":null},"messages":[{"id":"325667","messageId":"CAJo=hJtg0PAVHT1phbArdra8+4LfnEEuaj3fBid==BXkZghi8g@mail.gmail.com","threadId":"46523","inReplyTo":null,"subject":"Re: reftable [v6]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-07T01:47:06Z","receivedAt":"2017-08-07T01:47:36Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"6th 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 v5:\n- extensions.refStorage = reftable is used to select this format.\n\n- Log records can be explicitly deleted (for refs/stash).\n- Log records may use Michael Haggerty's chained idea to compress before zlib.\n  This saved ~5.8% on one of my example repositories.\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 a SHA-1 is referred to by at least\n  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 blocks.  Prefix compression\nis used within a single block to reduce disk space.  Block size is\ntunable 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 |   34.4 M |     55.2%  | 33 bytes | 8 bytes\nrails      |       1.8 M |    1.1 M |     57.7%  | 29 bytes | 6 bytes\ngit        |      78.7 K |   44.0 K |     60.0%  | 50 bytes | 6 bytes\ngit (heads)|       332 b |    274 b |     83.1%  | 34 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_blocks*\n    ref_index?\n    obj_blocks*\n    obj_index?\n    log_blocks*\n    log_index?\n    footer\n\nA log-only file omits the `ref_blocks`, `ref_index`, `obj_blocks` and\n`obj_index` sections, containing only the file header and log blocks:\n\n    first_block {\n      header\n    }\n    log_blocks*\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 `block_size` is arbitrarily determined by the writer, and does not\nhave to be a power of 2.  The block size must be larger than the\nlongest 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### 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\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 (see below), these fields can\norder the files such that the prior file's `max_update_index + 1` is\nthe 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    uint16( restart_count )\n    uint24( restart_offset )+\n    ref_record+\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 almost always shorter than the file's\n`block_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\nA variable number of 3-byte `restart_offset` follows.  Offsets are\nrelative to the start of the block and refer to the first byte of any\n`ref_record` whose name has not been prefix compressed.  Entries in\nthe `restart_offset` list must be sorted, ascending.  Readers can\nstart linear scans from any of these records.\n\nA variable number of `ref_record` fill the remainder 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.\n\nThe end of the block may be filled with `padding` NUL bytes to fill\nout the block to the common `block_size` as specified in the file\nheader.  Padding may be necessary to ensure the following block starts\nat a block alignment, and does not spill into the tail of this block.\nPadding may be omitted if the block is the last block of the file, and\nthere is no index block.  This allows reftable to efficiently scale\ndown to a small number of refs.\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 to copy from\n`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`: symref and text: `varint( text_len ) text`\n\nSymbolic references use `0x3` with a `text` string starting with `\"ref: \"`,\nfollowed by the complete name of the reference target.  No\ncompression is applied to the target name.  Other types of contents\nthat are also reference like, such as `FETCH_HEAD` and `MERGE_HEAD`,\nmay also be stored using type `0x3`.\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 index blocks (3rd level) or ref\nblocks (leaf level).  Disk reads required to access a ref go up with\nhigher index levels.  To acheive constant O(1) disk seeks for lookups\nthe index must be a single level, which is permitted to exceed the\nfile's configured `block_size`.\n\nIf present, the ref index block(s) appears after the last ref block.\nThe prior ref block should be padded to ensure the ref index starts on\na block alignment.\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 requires\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\nIndex block format:\n\n    uint32( (1 << 31) | block_len )\n    uint16( restart_count )\n    uint24( restart_offset )+\n    index_record+\n    padding?\n\nThe index block header starts with the high bit set.  This identifies\nthe block as an index block, and not as a ref block, log block or file\nfooter.  The `block_len` field in an index block is 31-bits network\nbyte order, and allowed to occupy space normally used by the block\ntype in other blocks.  This supports single-level indexes\nsignificantly larger than the file's `block_size`, up to 1.9 GiB.\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 the 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\nWhen object blocks are present the ref index block is padded with\n`padding` to maintain alignment for the next block. No padding is\nnecessary if log blocks or the file trailer follows the ref index.\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` address is for the 1st level root of the ref\nindex.\n\n### Obj block format\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    uint16( restart_count )\n    uint24( restart_offset )+\n    obj_record+\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\nObject blocks should be block aligned, according to `block_size` from\nthe file header.  The `padding` field is filled with NULs to maintain\nalignment for the next block.\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( block_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 `block_count` number of block identifiers for ref\nblocks.  For 1-7 blocks the block count is stored in `cnt_3`.  When\n`cnt_3 = 0` the actual block 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 be 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 `block_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 `block_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 `block_delta` is the absolute block identifier counting from\nthe start of the file.  The position of that block can be obtained by\n`block_delta[0] * block_size`.  Additional `block_delta` entries are\nsorted ascending and relative to the prior entry, e.g.  a reader would\nperform:\n\n    block_id = block_delta[0]\n    prior = block_id\n    for (j = 1; j < block_count; j++) {\n      block_id = prior + block_delta[j]\n      prior = block_id\n    }\n\nWith a `block_id` in hand, a reader must linearly scan the ref block\nat `block_id * block_size` position in the file, starting from the first\n`ref_record`, testing each reference's SHA-1s (for `value_type = 0x1`\nor `0x2`) for full equality.  Faster searching by SHA-1 within a\nsingle ref block is not supported by the reftable format.  Smaller\nblock sizes reduces the number of candidates this step must 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\nThe obj index should be block aligned, according to `block_size` from\nthe file header.  This requires padding the last obj block to maintain\nalignment.\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 block sizes are variable in size, and\ndo not match the `block_size` specified in the file header or footer.\nWriters should choose an appropriate buffer size to prepare a log block\nfor deflation, such as `2 * block_size`.\n\nA log block is written as:\n\n    'g'\n    uint24( block_len )\n    zlib_deflate {\n      uint16( restart_count )\n      uint24( restart_offset )+\n      log_record+\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\nUnlike ref blocks, log blocks are written at any alignment, without\npadding.  The first log block immediately follows the end of the prior\nblock, which omits its trailing padding.  In very small files the log\nblock may appear in the first block.\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 index 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 | log_chained )?\n\n\n    log_data {\n      old_id\n      new_id\n      varint( time_seconds )\n      sint16( tz_offset )\n      varint( name_length    )  name\n      varint( email_length   )  email\n      varint( message_length )  message\n    }\n\n    log_chained {\n      old_id\n      varint( time_seconds )\n      not_same_committer {\n        sint16( tz_offset )\n        varint( name_length    )  name\n        varint( email_length   )  email\n      }?\n      not_same_message {\n        varint( message_length )  message\n      }?\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- `0x2..0x3`: reserved for future use.\n- `0x4..0x7`: `log_chained`, with conditional members.\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 time in seconds since epoch (Jan 1, 1970)\n- 2-byte timezone offset in minutes (signed)\n- varint string of committer's name\n- varint string of committer's email\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 `>`, its 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\nFor `log_type = 0x4..0x7` the `log_chained` section is used instead to\ncompress information that already appeared in a prior log record.  The\n`log_chained` always includes `old_id` for this record, as `new_id` is\nimplied by the prior (by file order, more recent) record's `old_id`.\n\nThe `not_same_committer` block appears if `log_type & 0x1` is true,\n`not_same_message` block appears if `log_type & 0x2` is true.  When\none of these blocks is missing, its values are implied by the prior\n(more recent) log record.\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 only an additional 20\nbytes per reference.\n\n### Low overhead\n\nA reftable with very few references (e.g. git.git with 5 heads)\nis 274 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 reduces 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 by repositories.\nSHA-1s are stored twice when obj blocks are present, avoiding disk\nseeks for the common cases of scan and lookup by name.\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_UF4paF\n    00000002_bUVgy4\n\nwhere reftable files are named by a unique name such as produced by\nthe function:\n\n    mktemp \"${update_index}_XXXXXX\"\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_UF4paF\n    00000002_bUVgy4\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### 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 new reftable `${update_index}_XXXXXX`, including log entries.\n5. Copy `refs` to `refs.lock`, appending file from (4).\n6. 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 entry shadows the reference in 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 new 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.  Write the new stack to `refs.lock`, replacing `B` and `C` with the\n    file from (4).\n8.  Rename `refs.lock` to `refs`.\n9.  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 aligning 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":"325721","messageId":"CAGZ79kZO517Bg+O2z3dr+oHqO_av1__FU3h9bP=rhXJUSDnRjA@mail.gmail.com","threadId":"46523","inReplyTo":"CAJo=hJtg0PAVHT1phbArdra8+4LfnEEuaj3fBid==BXkZghi8g@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Stefan Beller","fromEmail":"sbeller@google.com","sentAt":"2017-08-07T18:27:17Z","receivedAt":"2017-08-07T18:27:28Z","isPatch":false,"sender":{"key":"stefanbeller@gmail.com","avatar":"https://avatars.githubusercontent.com/u/455868?v=4"},"body":"On Sun, Aug 6, 2017 at 6:47 PM, Shawn Pearce <spearce@spearce.org> wrote:\n> 6th 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 v5:\n> - extensions.refStorage = reftable is used to select this format.\n>\n> - Log records can be explicitly deleted (for refs/stash).\n> - Log records may use Michael Haggerty's chained idea to compress before zlib.\n>   This saved ~5.8% on one of my example repositories.\n\nSome observations:\n\nAlso the bits in the records changed in v5 or v6:\n  0x0..0x3 is valid for a ref,\n  obj records have a ccnt\n  0x0, 0x1, 0x4..0x7 are used in the logs\n\nWe have the following block indicators:\n  'r'  ref block\n  'o' object block\n  'g' log block\n\n  high bit for any index.\n\nWithout prior knowledge an index doesn't indicate if it\nindexes refs, objects or logs. To find out, one must follow\nan arbitrary entry which points to either an index again\nor at a block marked with 'r', 'o' or 'g'.\n\nOkay with me.\n\n> The index may be organized into a multi-level index, where ...\n> which may in turn point to either index blocks (3rd level) or ref blocks (leaf level).\n\nSo we allow 3 levels at most?\n\nThe file format structure marks the indexes '?', should that be\nrather '*' to indicate there can be more than one index block?\n"},{"id":"325723","messageId":"CAJo=hJvsdkrv6uELF0BHxqk4+as8-tr1bdYNHiQ3paTmn=2sRw@mail.gmail.com","threadId":"46523","inReplyTo":"CAGZ79kZO517Bg+O2z3dr+oHqO_av1__FU3h9bP=rhXJUSDnRjA@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-07T18:30:29Z","receivedAt":"2017-08-07T18:30:58Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Mon, Aug 7, 2017 at 11:27 AM, Stefan Beller <sbeller@google.com> wrote:\n> On Sun, Aug 6, 2017 at 6:47 PM, Shawn Pearce <spearce@spearce.org> wrote:\n>> 6th 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>> The index may be organized into a multi-level index, where ...\n>> which may in turn point to either index blocks (3rd level) or ref blocks (leaf level).\n>\n> So we allow 3 levels at most?\n\nNo, its just an example. Large ref sets with small block size need 4\nlevels. Or more.\n\n> The file format structure marks the indexes '?', should that be\n> rather '*' to indicate there can be more than one index block?\n\nWill fix in the next respin of the document, thanks.\n"},{"id":"325785","messageId":"20170808072859.iho6uns5q7mc5ydc@sigill.intra.peff.net","threadId":"46523","inReplyTo":"CAJo=hJtg0PAVHT1phbArdra8+4LfnEEuaj3fBid==BXkZghi8g@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Jeff King","fromEmail":"peff@peff.net","sentAt":"2017-08-08T07:28:59Z","receivedAt":"2017-08-08T07:29:10Z","isPatch":false,"sender":{"key":"peff@peff.net","avatar":"https://avatars.githubusercontent.com/u/45925?v=4"},"body":"On Sun, Aug 06, 2017 at 06:47:06PM -0700, Shawn Pearce wrote:\n\n> Changes from v5:\n> - extensions.refStorage = reftable is used to select this format.\n\nThanks, I think this is a better scheme going forward. Just a few notes\non compatibility while I'm thinking about it:\n\n  - existing versions will complain that they don't know what the\n    \"refStorage\" extension is\n\n  - presumably we'd add new code that recognizes the extension, and then\n    makes sure the value is something we understand.\n\n  - then we'd finally mark \"reftable\" as understood once we had an\n    implementation. We _could_ then also check other config (like\n    \"reftable.*\") and complain about unknown keys. But I think we could\n    declare any such keys as optional, and just rely on the version\n    number inside the reftable file for parsing it.\n\n-Peff\n"},{"id":"325831","messageId":"xmqqtw1hc28z.fsf@gitster.mtv.corp.google.com","threadId":"46523","inReplyTo":"CAJo=hJtg0PAVHT1phbArdra8+4LfnEEuaj3fBid==BXkZghi8g@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2017-08-08T19:01:48Z","receivedAt":"2017-08-08T19:01:56Z","isPatch":false,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"I notice that you raised the location of restart table within a\nblock in this iteration (or maybe it happened in v5).  \n\nThis forces you to hold all contents in core before the first byte\nis written out.  You start from the first entry (which will become\nthe first restart entry), emit a handful as prefix compressed\nentries, emit a full entry (which will become the next restart\nentry), ... until you have enough to fill both the data and the\nrestart table, then start writing from the header (which needs the\nlength of the block), restart table and then data.\n\nI think it is OK to do so for the blocks whose size is limited to\n16M, but I wonder if it is sensible to do the same for the index\nblock whose limit is 2G.  If you keep the restart table after the\ndata, then you could stream out the entries as you emit, write the\nrestart table, and then seek back to fix the length in the header,\nwithout holding the 2G in core, no?\n\n"},{"id":"325833","messageId":"xmqqpoc5c15v.fsf@gitster.mtv.corp.google.com","threadId":"46523","inReplyTo":"CAJo=hJtg0PAVHT1phbArdra8+4LfnEEuaj3fBid==BXkZghi8g@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2017-08-08T19:25:16Z","receivedAt":"2017-08-08T19:25:25Z","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> For `log_type = 0x4..0x7` the `log_chained` section is used instead to\n> compress information that already appeared in a prior log record.  The\n> `log_chained` always includes `old_id` for this record, as `new_id` is\n> implied by the prior (by file order, more recent) record's `old_id`.\n>\n> The `not_same_committer` block appears if `log_type & 0x1` is true,\n> `not_same_message` block appears if `log_type & 0x2` is true.  When\n> one of these blocks is missing, its values are implied by the prior\n> (more recent) log record.\n\nTwo comments.\n\n * not-same-committer would be what I would use when I switch\n   timezones, even if I stay to be me, right?  I am just wondering\n   if it is clear to everybody that \"committer\" in that phrase is a\n   short-hand for \"committer information other than the timestamp\".\n\n * Should the set of entries that are allowed to use of \"chained\"\n   log be related to the set of entries that appear in the restart\n   table in any way?  For a reader that scans starting at a restart\n   point, it would be very cumbersome if the entry were chained from\n   the previous entry, as it would force it to backtrack entries to\n   find the first non-chained log entry.  A simple \"log_chained must\n   not be used for an entry that appear in the restart table\" rule\n   would solve that, but I didn't see it in the document.\n\n\n\n"},{"id":"325869","messageId":"CAJo=hJsyoFeCQbeJ=2XCRcE1U0zYaRr8VvzXHwkPwisdfUm71Q@mail.gmail.com","threadId":"46523","inReplyTo":"xmqqtw1hc28z.fsf@gitster.mtv.corp.google.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-08T22:27:05Z","receivedAt":"2017-08-08T22:27:31Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Tue, Aug 8, 2017 at 12:01 PM, Junio C Hamano <gitster@pobox.com> wrote:\n> I notice that you raised the location of restart table within a\n> block in this iteration (or maybe it happened in v5).\n>\n> This forces you to hold all contents in core before the first byte\n> is written out.  You start from the first entry (which will become\n> the first restart entry), emit a handful as prefix compressed\n> entries, emit a full entry (which will become the next restart\n> entry), ... until you have enough to fill both the data and the\n> restart table, then start writing from the header (which needs the\n> length of the block), restart table and then data.\n>\n> I think it is OK to do so for the blocks whose size is limited to\n> 16M, but I wonder if it is sensible to do the same for the index\n> block whose limit is 2G.  If you keep the restart table after the\n> data, then you could stream out the entries as you emit, write the\n> restart table, and then seek back to fix the length in the header,\n> without holding the 2G in core, no?\n\nYes. I'm torn on the ordering: restart table first or restart table last.\n\nThe advantage of it first is the reader can immediately work with it,\nwithout necessarily touching the rest of the block. The disadvantage\nis a writer can only stream at block sizes, as the writer is forced to\nbuffer the entire block. As it happens my implementation in JGit\nbuffers the entire block anyway, so this didn't really factor as an\nissue for me.\n\nGiven that the index can now also be multi-level, I don't expect to\nsee a 2G index. A 2G index forces the reader to load the entire 2G to\ntake advantage of the restart table. It may be more efficient for such\na reader to have had the writer make a mutli-level index, instead of a\nsingle monster index block. And so perhaps the writer shouldn't make a\n2G index block that she is forced to buffer. :)\n\nPerhaps I'll move it back to the tail of the block. I can see the\nstreaming writer code is maybe more straightforward that way.\n"},{"id":"325871","messageId":"CAJo=hJusmthiWG6sQ27_anZ7DVbEKGNHyOCUigWP6Naj4ThDvg@mail.gmail.com","threadId":"46523","inReplyTo":"xmqqpoc5c15v.fsf@gitster.mtv.corp.google.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-08T22:30:28Z","receivedAt":"2017-08-08T22:30:55Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Tue, Aug 8, 2017 at 12:25 PM, Junio C Hamano <gitster@pobox.com> wrote:\n> Shawn Pearce <spearce@spearce.org> writes:\n>\n>> For `log_type = 0x4..0x7` the `log_chained` section is used instead to\n>> compress information that already appeared in a prior log record.  The\n>> `log_chained` always includes `old_id` for this record, as `new_id` is\n>> implied by the prior (by file order, more recent) record's `old_id`.\n>>\n>> The `not_same_committer` block appears if `log_type & 0x1` is true,\n>> `not_same_message` block appears if `log_type & 0x2` is true.  When\n>> one of these blocks is missing, its values are implied by the prior\n>> (more recent) log record.\n>\n> Two comments.\n>\n>  * not-same-committer would be what I would use when I switch\n>    timezones, even if I stay to be me, right?\n\nCorrect. This is based on the theory that the timezone in a reflog is\nactually the system timezone, not your timezone. If you push to a\nremote system, that system's reflog will be using that system's\ntimezone, not your timezone. So you aren't really that different, and\nwe can compress the timezone part away. Also, if you do move\ntimezones, you are likely to remain in that timezone for some period\nof time, and such we can compress many log records again with the same\ntimezone+name+email.\n\nIts ancient history from my research with \"pack v4\", but people don't\nreally change timezones very often in the Git committer data. I\nsuspect its even more true with reflog data.\n\n>  I am just wondering\n>    if it is clear to everybody that \"committer\" in that phrase is a\n>    short-hand for \"committer information other than the timestamp\".\n\nMaybe not. I will try to come up with another shorthand name for this.\n\n>  * Should the set of entries that are allowed to use of \"chained\"\n>    log be related to the set of entries that appear in the restart\n>    table in any way?  For a reader that scans starting at a restart\n>    point, it would be very cumbersome if the entry were chained from\n>    the previous entry, as it would force it to backtrack entries to\n>    find the first non-chained log entry.  A simple \"log_chained must\n>    not be used for an entry that appear in the restart table\" rule\n>    would solve that, but I didn't see it in the document.\n\nGood catch!  This is implemented as you described in JGit (for the\nreasons you described), but not documented. I'll fix it.\n"},{"id":"325879","messageId":"xmqqy3qt8wi0.fsf@gitster.mtv.corp.google.com","threadId":"46523","inReplyTo":"CAJo=hJsyoFeCQbeJ=2XCRcE1U0zYaRr8VvzXHwkPwisdfUm71Q@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2017-08-08T23:34:15Z","receivedAt":"2017-08-08T23:34:24Z","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> Given that the index can now also be multi-level, I don't expect to\n> see a 2G index. A 2G index forces the reader to load the entire 2G to\n> take advantage of the restart table. It may be more efficient for such\n> a reader to have had the writer make a mutli-level index, instead of a\n> single monster index block. And so perhaps the writer shouldn't make a\n> 2G index block that she is forced to buffer. :)\n\nAh, OK, then it is sensible to have all table blocks to have the\nsame format, and restart at the beginning to help readers would be a\nfine choice.  For the same \"let's make them as consistent\" sake, I\nam tempted to suggest that we lift \"the index block can be 2G\" and\nhave it also be within uint_24(), perhaps?  Otherwise the readers\nwould have to read (or mmap) the whole 2G.\n"},{"id":"325881","messageId":"CAGZ79kbZiUDmp64FLYPOvT-Y4a8+YJF=fanYTB8Urxif9h6ZTg@mail.gmail.com","threadId":"46523","inReplyTo":"CAJo=hJvsdkrv6uELF0BHxqk4+as8-tr1bdYNHiQ3paTmn=2sRw@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Stefan Beller","fromEmail":"sbeller@google.com","sentAt":"2017-08-08T23:52:47Z","receivedAt":"2017-08-08T23:52:55Z","isPatch":false,"sender":{"key":"stefanbeller@gmail.com","avatar":"https://avatars.githubusercontent.com/u/455868?v=4"},"body":"On Mon, Aug 7, 2017 at 11:30 AM, Shawn Pearce <spearce@spearce.org> wrote:\n> On Mon, Aug 7, 2017 at 11:27 AM, Stefan Beller <sbeller@google.com> wrote:\n>> On Sun, Aug 6, 2017 at 6:47 PM, Shawn Pearce <spearce@spearce.org> wrote:\n>>> 6th 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>>> The index may be organized into a multi-level index, where ...\n>>> which may in turn point to either index blocks (3rd level) or ref blocks (leaf level).\n>>\n>> So we allow 3 levels at most?\n>\n> No, its just an example. Large ref sets with small block size need 4\n> levels. Or more.\n\nA malicious (or buggy) writer can produce indexes pointing to\neach other producing a circle. (Who would do that?)\n\nA reader should  - instead of segfaulting due to unbounded\nrecursion or being stuck in an infinite loop - ignore the indexes\nin this case and fallback to the slow non-indexed behavior,\ni.e. while the file format allows for unbounded levels, a reader\nshould not.\n"},{"id":"325883","messageId":"CAJo=hJt5b=e1-k7FnMixe7vqH8V0ynCHQU80aWKAMJzghU+s3A@mail.gmail.com","threadId":"46523","inReplyTo":"xmqqy3qt8wi0.fsf@gitster.mtv.corp.google.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-08-09T00:01:49Z","receivedAt":"2017-08-09T00:02:19Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Tue, Aug 8, 2017 at 4:34 PM, Junio C Hamano <gitster@pobox.com> wrote:\n> Shawn Pearce <spearce@spearce.org> writes:\n>\n>> Given that the index can now also be multi-level, I don't expect to\n>> see a 2G index. A 2G index forces the reader to load the entire 2G to\n>> take advantage of the restart table. It may be more efficient for such\n>> a reader to have had the writer make a mutli-level index, instead of a\n>> single monster index block. And so perhaps the writer shouldn't make a\n>> 2G index block that she is forced to buffer. :)\n>\n> Ah, OK, then it is sensible to have all table blocks to have the\n> same format, and restart at the beginning to help readers would be a\n> fine choice.  For the same \"let's make them as consistent\" sake, I\n> am tempted to suggest that we lift \"the index block can be 2G\" and\n> have it also be within uint_24(), perhaps?  Otherwise the readers\n> would have to read (or mmap) the whole 2G.\n\nGah. I just finished moving the restart table back to the end of the block. :)\n\nHowever, I think I can agree with the index fitting into the uint24\nsize of 15M, and asking writers making an index that exceeds that to\nuse multi-level indexing.\n"},{"id":"326268","messageId":"7271a556-8aaf-ae69-8b45-45efbc5f91a5@alum.mit.edu","threadId":"46523","inReplyTo":"CAJo=hJtg0PAVHT1phbArdra8+4LfnEEuaj3fBid==BXkZghi8g@mail.gmail.com","subject":"Re: reftable [v6]: new ref storage format","fromName":"Michael Haggerty","fromEmail":"mhagger@alum.mit.edu","sentAt":"2017-08-14T12:13:23Z","receivedAt":"2017-08-14T12:13:36Z","isPatch":false,"sender":{"key":"mhagger@alum.mit.edu","avatar":"https://avatars.githubusercontent.com/u/119718?v=4"},"body":"On 08/07/2017 03:47 AM, Shawn Pearce wrote:\n> 6th iteration of the reftable storage format.\n\nThanks!\n\n> Changes from v5:\n> - extensions.refStorage = reftable is used to select this format.\n> \n> - Log records can be explicitly deleted (for refs/stash).\n> - Log records may use Michael Haggerty's chained idea to compress before zlib.\n>   This saved ~5.8% on one of my example repositories.\n\nMeh. Do you think that's worth the complexity? The percentage savings\nwill presumably be even lower for repositories that store significant\ninformation in their reflog messages.\n\n> [...]\n> #### ref record\n> \n> A `ref_record` describes a single reference, storing both the name and\n> its value(s). Records are formatted as:\n> \n>     varint( prefix_length )\n>     varint( (suffix_length << 3) | value_type )\n>     suffix\n>     value?\n> \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`: symref and text: `varint( text_len ) text`\n> \n> Symbolic references use `0x3` with a `text` string starting with `\"ref: \"`,\n> followed by the complete name of the reference target.  No\n> compression is applied to the target name.  Other types of contents\n> that are also reference like, such as `FETCH_HEAD` and `MERGE_HEAD`,\n> may also be stored using type `0x3`.\n\nI'm still relatively negative on storing \"other\" references (except\n`HEAD`) in reftable. Here are my thoughts:\n\n* \"Other\" references are not considered for reachability, so there\n  is no need for their modification to be done atomically.\n\n* \"Other\" references don't have or need reflogs.\n\n* The refs API would have to provide a way for other Git code to\n  read and write \"other\" references including their extra\n  information, and the users of that information would have to\n  be rewritten to use the new API.\n\n* Presumably there are other programs in the wild (e.g., scripts)\n  that want to read that information. They wouldn't be able to\n  extract it from reftable files themselves, so we would also have\n  to provide a command-line tool to read (and write?) such files.\n\n> Types `0x4..0x7` are reserved for future use.\n\nRegardless, I suggest allocating separate `value_type`s for generic\nsymrefs (which then wouldn't need a `ref: ` prefix) vs. for \"other\"\nreferences.\n\n> [...]\n> ### Ref index\n\nIt wasn't clear to me whether (in the case of a multi-level index) ref\nindex blocks have to be aligned in `block_size` blocks (both their\nmaximum size and their alignment). I don't see a reason for that to be\nrequired, though of course a compactor implementation might choose to\nblock-align these blocks based on the filesystem that is in use.\n\nFor that matter, I don't see an intrinsic reason that object blocks or\nobject index blocks need to be block aligned.\n\nIn fact, the only way I can see that the current reftable proposal makes\nuse of `block_size` is so that `obj_record`s can record `block_delta` in\nunits of `block_size` rather than in units of bytes. (And given that I'm\nskeptical about the value of the object index, that justification seems\nthin.)\n\nI totally accept that *you* want to align your blocks, and I'm totally\nsupportive of a format that permits a reftable compactor to write\nreftables that are block-aligned. It just still seems to me that it\nimposes more complexity than necessary on *other* reftable compactor\nimplementations that don't care about block alignment.\n\nAside from the object index, I think it would be straightforward to\nwrite a reftable reader that is totally ignorant of `block_size`.\n\nSo unless I've overlooked something, I think the following plan wouldn't\ncause you any extra trouble, but would make it easier to implement a\ncompactor that doesn't care about block sizes or object indexes:\n\nIf a reftable has an object index, then `block_size` must be specified,\nand ref blocks *must* be aligned to start at multiples of `block_size`.\n\nHowever, if a reftable has no object index, then its `block_size` is\nonly a hint about the typical block size; e.g., \"if you want to read a\nfull block, then try reading `block_size` and you'll probably get the\nwhole thing\". And if `block_size` is zero, then readers get no guidance\nabout the typical block size (which would be just fine for an mmap-based\nreader).\n\nEssentially, choices about block alignment would become a\nquality-of-implementation issue for reftable compactors, and readers\nwould hardly need to care.\n\n> [...]\n> #### index record\n> \n> An index record describes the last entry in another block.\n> Index records are written as:\n> \n>     varint( prefix_length )\n>     varint( (suffix_length << 3) | 0 )\n>     suffix\n>     varint( block_position )\n> \n> Index records use prefix compression exactly like `ref_record`.\n> \n> Index records store `block_position` after the suffix, specifying the\n> absolute position in bytes (from the start of the file) of the block\n> that ends with this reference.\n\nIs there a reason that the index lists the *last* refname that is\ncontained in a block rather than the *first* refname? I can't think of a\nreason to choose one vs. the other, but your choice was initially\nsurprising. I don't think it matters either way; I was just curious.\n\nDo I understand correctly that all `block_position`s are *byte*\naddresses, even in the `ref_index` where they should all be multiples of\nthe block size (except the zeroth one)? I think that's OK, but note that\nit will waste more than a byte per `ref_index` and `obj_index` record,\non average.\n\n> Readers must examine the block header at `block_position` to determine\n> if the next block is another level index block, or the leaf-level ref\n> block.\n\nFor scanning through a whole namespace, like `refs/tags/`, I guess you\nonly need to use a binary search to find the beginning of the range.\nThen you would read serially forwards from there, continuing from one\n`ref_block` to the next, until you find a refname that doesn't start\nwith `refs/tags/`. In other words, there is no reason to binary search\nto find the end of the namespace, correct? [1]\n\nThe same approach would be used to scan the reflog of a reference.\n\n[1] I suppose binary searching to find the end of the namespace might be\nuseful for a high-latency filesystem, as you could initiate a pre-fetch\nfor all of the storage blocks that are expected to be needed rather than\ninitiating the read of the next block only after having processed the\nprevious block.\n\n> [...]\n> #### log record\n> [...]\n>     log_chained {\n>       old_id\n>       varint( time_seconds )\n>       not_same_committer {\n>         sint16( tz_offset )\n>         varint( name_length    )  name\n>         varint( email_length   )  email\n>       }?\n>       not_same_message {\n>         varint( message_length )  message\n>       }?\n>     }\n> ```\n> \n> Log 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> - `0x2..0x3`: reserved for future use.\n> - `0x4..0x7`: `log_chained`, with conditional members.\n> \n> [...]\n> For `log_type = 0x4..0x7` the `log_chained` section is used instead to\n> compress information that already appeared in a prior log record.  The\n> `log_chained` always includes `old_id` for this record, as `new_id` is\n> implied by the prior (by file order, more recent) record's `old_id`.\n> \n> The `not_same_committer` block appears if `log_type & 0x1` is true,\n> `not_same_message` block appears if `log_type & 0x2` is true.  When\n> one of these blocks is missing, its values are implied by the prior\n> (more recent) log record.\n\nJust to make sure that we are on the same page...\n\n`old_id` and `new_id` in adjacent reflog entries are not always\nidentical. If you run `git reflog expire` or `git reflog delete` without\nthe `--rewrite` option, then the to-be-deleted entries are just dropped\nwithout changing the neighboring entries to chain together again.\n\nThis would have to be supported in your proposal by writing a full\n`log_data` record for the entry following such a gap.\n\n> [...]\n> #### Importing logs\n> \n> When importing from `$GIT_DIR/logs` writers should globally order all\n> log records roughly by timestamp while preserving file order, and\n> assign unique, increasing `update_index` values for each log line.\n> Newer log records get higher `update_index` values.\n> \n> Although an import may write only a single reftable file, the reftable\n> file must span many unique `update_index`, as each log line requires\n> its own `update_index` to preserve semantics.\n\nThinking out loud here: A really high-quality importer might want to\ngroup together, under the same `update_index`, ref updates that are\nthought originally to have been done in the same transaction.\n\n* Only group entries with the same timestamps and log messages\n  should be grouped together.\n\n* There should not be more than one update to a particular\n  reference in a single transaction.\n\n* Ideally, it would avoid creating states between `update-index`es\n  where references D/F-conflict with each other. (Given that reflogs\n  can be expired, this is not always possible in the general case.)\n\n* It could theoretically even reconstruct \"branch rename\" operations\n  that required temporary reference names into a single `update_index`.\n\nBut I doubt that it is worth the effort. (The whole idea gives me nasty\nflashbacks from working on cvs2svn/cvs2git.)\n\n> [...]\n> ### Layout\n> \n> The `$GIT_DIR/refs` path is a file when reftable is configured, not a\n> directory.  This prevents loose references from being stored.\n> \n> A collection of reftable files are stored in the `$GIT_DIR/reftable/`\n> directory:\n> \n>     00000001_UF4paF\n>     00000002_bUVgy4\n> \n> where reftable files are named by a unique name such as produced by\n> the function:\n> \n>     mktemp \"${update_index}_XXXXXX\"\n\nPlease note that if reflogs are compacted into a separate \"reflog-only\"\nfile, then the same `update_index` might appear in the filename of both\na \"reflog-only\" file and a value-only file. I don't think that this is a\nproblem, but we shouldn't bake assumptions about uniqueness into the system.\n\nI'm a little bit worried that users might automatically think that a\nfilename that includes a string like `UF4paF` is a temporary file and\n\"clean it up\" (with disastrous consequences). It might be prudent to\ngive the files names that don't look so garbagy.\n\nAnd wouldn't it be nice to tack a filename extension onto the end of\nthese filenames to make them more easily recognizable?\n\n> The stack ordering file is `$GIT_DIR/refs` and lists the current\n> files, one per line, in order, from oldest (base) to newest (most\n> recent):\n> \n>     $ cat .git/refs\n>     00000001_UF4paF\n>     00000002_bUVgy4\n> \n> Readers must read `$GIT_DIR/refs` to determine which files are\n> relevant right now, and search through the stack in reverse order\n> (last reftable is examined first).\n> \n> Reftable files not listed in `refs` may be new (and about to be added\n> to the stack by the active writer), or ancient and ready to be pruned.\n\nIt might be good to think about how readers should work. The easy\nimplementation would be:\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 (with some checks to avoid\n   infinite loops).\n4. Read from the now-open files as long as you need to.\n\nThis would give you a self-consistent snapshot of the global reference\nstate. However, a long-running program (especially one dealing with\nreachability) might want to check at strategic moments that the `refs`\nfile hasn't changed out from under it while it was running, or even lock\nthe `refs` file during critical operations.\n\nIt would be possible to avoid opening all of the reftable files right\naway in the hope that the reference that you seek is in one of the top\nfew files. But this quickly gets tricky because you might read some\nreferences from the top reftable, then need to dig deeper for another\nreference only to find out that one of the deeper files is no longer in\nthe stack. So in one program run you might end up seeing reference\nvalues from two different snapshots.\n\n> [...]\n\nMichael\n"}]}