{"thread":{"id":"46405","subject":"reftable [v2]: new ref storage format","startedAt":"2017-07-17T15:02:14Z","lastAt":"2017-07-23T23:49:20Z","messageCount":9,"participants":["Shawn Pearce","Stefan Beller","Junio C Hamano","Ævar Arnfjörð Bjarmason"],"isPatch":false,"patchVersion":null,"patchTotal":null},"messages":[{"id":"324641","messageId":"CAJo=hJtTp2eA3z9wW9cHo-nA7kK40vVThqh6inXpbCcqfdMP9g@mail.gmail.com","threadId":"46405","inReplyTo":null,"subject":"reftable [v2]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-07-17T15:01:44Z","receivedAt":"2017-07-17T15:02:14Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"This is an updated draft after discussion on list with Peff, Michael\nHaggerty, and Dave Borowitz.\n\nYou can read a rendered version of this here:\nhttps://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md\n\nBiggest changes from the first proposal are:\n\n- reflog is now integrated into reftable\n- block headers slightly different\n- Peff's stack management idea is used\n- Michael's compaction idea is used\n\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- Efficient lookup of an entire namespace, such as `refs/tags/`.\n- Occupy less disk space for large repositories.\n- Support atomic push `O(size_of_update)` operations.\n- Combine reflog storage with ref storage.\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\n-----------|------------:|---------:|-----------:|---------:\nandroid    |      62.2 M |   27.7 M |     44.4%  | 33 bytes\nrails      |       1.8 M |  896.2 K |     47.6%  | 29 bytes\ngit        |      78.7 K |   27.9 K |     40.0%  | 43 bytes\ngit (heads)|       332 b |    222 b |     66.9%  | 37 bytes\n\nScan (read 866k refs) and lookup (single ref from 866k refs):\n\nformat      | scan    | lookup\n------------|--------:|---------------:\npacked-refs |  380 ms | 375420.0 usec\nreftable    |  125 ms |     42.3 usec\n\nSpace used for 149,932 log entries on 43,061 refs,\nreflog vs. reftable:\n\nformat        | size  | avg log\n--------------|------:|-----------:\n$GIT_DIR/logs | 173 M | 1209 bytes\nreftable      |   4 M |   30 bytes\n\n## Details\n\n### Peeling\n\nReferences in a reftable are always peeled.\n\n### Reference name encoding\n\nReference names should be encoded with UTF-8.\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 basic structure:\n\n    first_block {\n      header\n      first_ref_block\n    }\n    ref_blocks*\n    ref_index?\n    log_blocks*\n    log_index?\n    footer\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\n(64k) can yield better compression.\n\nThe largest block size is `16777215` bytes (15.99 MiB).\n\n### Header\n\nA 8-byte header appears at the beginning of the file:\n\n    '\\1REF'\n    uint8( version_number = 1 )\n    uint24( block_size )\n\nThe `block_size` and all other uint fields are in network byte order.\n\n### First ref block\n\nThe first ref block shares the same block as the file header, and is 8\nbytes smaller than all other blocks in the file.  The first block\nimmediately begins after the file header, at offset 8.\n\n### Ref block format\n\nA ref block is written as:\n\n    'r'\n    uint24 ( block_len )\n    ref_record*\n    uint32( restart_offset )*\n    uint16( number_of_restarts )\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 8 bytes\nfor the file header.\n\nThe 4-byte block header is followed by a variable number of\n`ref_record`, describing reference names and values.  The format\nis described below.\n\nA variable number of 4-byte `restart_offset` values follows the\nrecords.  Offsets are relative to the start of the block (0 in first\nblock to include file header) and refer to the first byte of any\n`ref_record` whose name has not been prefixed compressed.  Readers can\nstart linear scans from any of these records.\n\nThe 2-byte `number_of_restarts + 1` stores the number of entries in\nthe `restart_offset` list.\n\nReaders can use the restart count to binary search between restarts\nbefore starting a linear scan.  The `number_of_restarts` field must be\nthe last 2 bytes of the block as specified by `block_len` from the\nblock header.\n\nThe end of the record 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, or\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 << 2) | 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 second varint carries both `suffix_length` and `value_type`.  The\n`suffix_length` value provides the number of bytes to copy from\n`suffix` to complete the reference name.\n\nThe `value` immediately follows.  Its format is determined by\n`value_type`, a 2 bit code, one of the 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 a varint length followed by a variable number\nof bytes to encode the complete reference target.  No compression is\napplied to the target name.\n\n### Ref index\n\nThe ref index stores the name of the last reference from every ref\nblock in the file, enabling constant O(1) disk seeks for all lookups.\nAny reference can be found by binary searching the index, identifying\nthe containing block, and searching within that block.\n\nIf present, the ref index block appears after the last ref block.  The\nprior ref block should be padded to ensure the ref index starts on a\nblock alignment.\n\nAn index block should only be written if there are at least 4 blocks\nin the file, as cold reads using the index requires 2 disk reads, and\nbinary searching <= 4 blocks also requires <= 2 reads.  Omitting the\nindex block from smaller files saves space.\n\nIndex block format:\n\n    uint32( (0x80 << 24) | block_len )\n    index_record*\n    uint32( restart_offset )*\n    uint16( number_of_restarts )\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 30-bits network\nbyte order, and allowed to occupy the space normally used by the block\ntype in other blocks.  This supports indexes significantly larger than\nthe file's `block_size`.\n\nThe `restart_offset` and `number_of_restarts` 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\nits a time-space tradeoff in both file size, and reader memory.\nIncreasing the block size in the writer decreases the index size.\n\nUnlike ref blocks, the index block is not padded.\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 << 2) )\n    suffix\n    varint( block_offset )\n\nIndex records use prefix compression exactly like `ref_record`.  The\n`suffix_length` is shifted 2 bits without a `type` to simplify unified\nreader/writer code for both block types.\n\nIndex records store `block_offset` after the suffix, specifying the\noffset in bytes (from the start of the file) of the block that ends\nwith this reference.\n\n#### Reading the index\n\nReaders loading the ref index must first read the footer (below) to\nobtain `ref_index_offset`. If not present, the offset will be 0.\n\n### Log block format\n\nA log block is written as:\n\n    'g'\n    uint24( block_len )\n    zlib_deflate {\n      log_record*\n      int32( restart_offset )*\n      int16( number_of_restarts )\n    }\n\nLog blocks look similar to ref blocks, except `block_type = 'g'`.\n\nThe 4-block header is followed by the deflated block contents using\nzlib deflate.  The `block_len` in the header is the inflated size\n(including 4-byte block header), and should be used by readers to\npreallocate the inflation output buffer.  Offsets within the block\n(e.g.  `restart_offset`) still include the 4-byte header.  Readers may\nprefer prefixing the inflation output buffer with the 4-byte header.\n\nWithin the deflate container, a variable number of `log_record`,\ndescribing reference changes.  The log record format is described\nbelow.  See ref block format (above) for a description of\n`restart_offset` and `number_of_restarts`.\n\nUnlike ref blocks, log blocks are written at any alignment, without\npadding.  The first log block immediately follows the end of the last\nref block, or the ref index.  In very small files the log block may\nappear in the first block.\n\nReaders must keep track of the bytes consumed by the inflater to know\nwhere the next log block begins.\n\n#### log record\n\nLog record keys are structured as:\n\n    ref_name '\\0' reverse_int32( time_sec )\n\nwhere `time_sec` is the update time in seconds since the epoch.  The\n`reverse_int32` function inverses the value so lexographical ordering\nthe network byte order time sorts more recent records first:\n\n    reverse_int(int32 t) {\n      return 0xffffffff - t;\n    }\n\nLog records have a similar starting structure to ref and index\nrecords, utilizing the same prefix compression scheme applied to the\nkey described above.  Like in an index record, a log record uses\n`value_type = 0x0`:\n\n    varint( prefix_length )\n    varint( (suffix_length << 2) | 0x0 )\n    suffix\n\n    old_id\n    new_id\n    sint16( tz_offset )\n    varint( name_length  )   name\n    varint( email_length )   email\n    varint( message_length ) message\n\nThe value data following the key suffix is complex:\n\n- two 20-byte SHA-1s (old id, new id)\n- 2-byte timezone offset (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 `int16(-480)` and `GMT+0230` is `int16(150)`.\n\nThe `message_length` may be 0, in which case there was no message\nsupplied for the update.\n\n#### Reading the log\n\nReaders accessing the log must first read the footer (below) to\ndetermine the `log_offset`.  The first block of the log begins at\n`log_offset` bytes since the start of the file.\n\nIn very small reftable files `log_offset`, may not be block aligned.\n\n### Log index\n\nThe log index stores the log key (`refname \\0 reverse_int32(time_sec)`)\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 first 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 5\nbytes longer to include `'\\0'` and the 4-byte `reverse_int32(time)`.\nRecords use `block_offset` to refer 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_offset`. If not present, the offset 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 36-byte footer appears at the end:\n\n    '\\1REF'\n    uint8( version_number = 1 )\n    uint24( block_size )\n\n    uint64( ref_index_offset )\n    uint64( log_offset )\n    uint64( log_index_offset )\n    uint32( CRC-32 of prior )\n\nIf a section is missing (e.g. ref index) the corresponding offset\nfield (e.g. `ref_index_offset`) will be 0.\n\n#### Reading the footer\n\nReaders must seek to `file_length - 36` 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 32 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++\n      val = val << 7\n      val = val | (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 maxium of `65536` restart points is supported in any type of block.\nThe `restart_count` field stores restart points `-1`, with a maxium\nvalue of `65535`.\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) uses\nonly 222 bytes for reftable vs. 332 bytes for packed-refs.  This\nsupports reftable scaling down, to be used for transaction logs\n(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 able to\ncompress against 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### 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.\n\n### Logs are read backwards\n\nLogs are frequently accessed backwards (most recent N records for master),\nso log records are grouped by reference, and sorted descending by time.\n\n## Repository format\n\nWhen reftable is stored in a file-backed Git repository, the stack is\nrepresented as a series of reftable files in the dedicated\n`$GIT_DIR/reftable/` directory:\n\n    stack\n    22b9ac56abe0ddc5f23d651fe4ef46343f338d20.ref\n    82f128e165c8afae9894aacf0219bc53a580f2ad.ref\n\nwhere `.ref` files are named by the SHA-1 hash of the contents of the\nreftable.\n\nThe `stack` file lists the current files, one per line, in order, from\noldest (base) to newest (most recent):\n\n    $ cat stack\n    82f128e165c8afae9894aacf0219bc53a580f2ad.ref\n    22b9ac56abe0ddc5f23d651fe4ef46343f338d20.ref\n\nReaders must read `stack` to determine which files are relevant right\nnow, and search through the stack in reverse order (last reftable is\nexamined first).\n\nFiles not listed in `stack` may be new (and about to be added to the\nstack 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. Atomically create `stack.lock`\n2. Copy current stack to `stack.lock`.\n3. Prepare new reftable in temp file `.refXXXXXXX`.\n   Include log entries.\n4. Rename (3) to `${sha1}.ref`.\n5. Append `${sha1}.ref` to `stack.lock`\n6. Atomically rename `stack.lock` to `stack`.\n\nBecause a single `stack.lock` file is used to manage locking, the\nrepository is single-threaded for writers.  Writers may have to\nbusy-spin (with some small backoff) around creating `stack.lock`,\nfor up to an acceptable wait period, aborting if the repository is too\nbusy to mutate.  Application servers wrapped around repositories (e.g.\nGerrit Code Review) can layer their own in memory thread lock/wait\nqueue to improve fairness.\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\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 `stack.lock` and read the `stack` file.\n2.  Obtain locks `B.lock` and `C.lock`.\n    Ownership of these locks prevents other processes from trying\nto compact these files.\n3.  Release `stack.lock`.\n4.  Compact `B` and `C` in temp file `.refXXXXXXX`.\n5.  Reacquire lock `stack.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 `.refXXXXXXX` to `X`.\n8.  Write the new stack to `stack.lock`, replacing `B` and `C` with `X`.\n9.  Atomically rename `stack.lock` to `stack`.\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 ratios achieved by reftable's simple encoding\n(e.g.  44%), without using a standard compression algorithm, it does\nnot seem necessary to add the complexity of bzip/gzip/zlib.\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":"324660","messageId":"CAGZ79kaFmxRSp1YBXc=6YEeDGUO-VLBF0yk+Bb0np7x80z_Vog@mail.gmail.com","threadId":"46405","inReplyTo":"CAJo=hJtTp2eA3z9wW9cHo-nA7kK40vVThqh6inXpbCcqfdMP9g@mail.gmail.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Stefan Beller","fromEmail":"sbeller@google.com","sentAt":"2017-07-17T18:53:23Z","receivedAt":"2017-07-17T18:53:30Z","isPatch":false,"sender":{"key":"stefanbeller@gmail.com","avatar":"https://avatars.githubusercontent.com/u/455868?v=4"},"body":"On Mon, Jul 17, 2017 at 8:01 AM, Shawn Pearce <spearce@spearce.org> wrote:\n\n> A ref block is written as:\n>\n>     'r'\n>     uint24 ( block_len )\n>     ref_record*\n>     uint32( restart_offset )*\n>     uint16( number_of_restarts )\n>     padding?\n>\n...\n>\n> The 2-byte `number_of_restarts + 1` stores the number of entries in\n> the `restart_offset` list.\n\nThis means uint16( number_of_restarts ) cannot be 0, but has to be 1\nto indicate no restarts?\n\nWhy do we need to be non-NUL here, but the padding is all NUL?\n\nWhen starting to write a block, we need to know exactly how large\nthe ref_records* and restart offsets need to be to put the\nnumber_of_restarts at the position as promised via block_len.\nThis sounds complicated unless I missed the obvious.\n\nGoing by this, would it rather make sense to omit the block_len\nand then scan backwards from *block_size-1 to find the first non-NUL\nand that will be the number_of_restarts?\n\nOr we could allow additional padding between ref_record and\nrestart_offsets, such that the writer implementation has wiggle room\nfor the restarting logic.\n\n>\n> #### log record\n>\n> Log record keys are structured as:\n>\n>     ref_name '\\0' reverse_int32( time_sec )\n>\n> where `time_sec` is the update time in seconds since the epoch.\n\nThe epoch ends 2038, which is in 21 years. (Did you just volunteer\nto fixup the time issues in 20 years?)\nIf possible I'd prefer a date to be encoded with more range available.\n\n>  The\n> `reverse_int32` function inverses the value so lexographical ordering\n> the network byte order time sorts more recent records first:\n>\n>     reverse_int(int32 t) {\n>       return 0xffffffff - t;\n>     }\n>\n> Log records have a similar starting structure to ref and index\n> records, utilizing the same prefix compression scheme applied to the\n> key described above.\n\nThe ref names itself are compressed, would we also want to compress\nthe timing information? The time_sec could be a varint indicating a delta\nto the previous change of a ref, or fixed to the epoch if it is the first change\nof that ref.\n\nJust to be clear, the ordering here would be\n\n  refs/heads/maint <number>\n  refs/heads/maint <smaller number>\n  ...\n  refs/heads/master <number>\n  refs/heads/master <smaller number>\n\nsuch that refs that have more than one entry in its reflog in a given\nrefstable file, would have perfect prefix compression for the ref?\n\n> ### Update transactions\n>\n> Although reftables are immutable, mutations are supported by writing a\n> new reftable and atomically appending it to the stack:\n>\n> 1. Atomically create `stack.lock`\n> 2. Copy current stack to `stack.lock`.\n> 3. Prepare new reftable in temp file `.refXXXXXXX`.\n>    Include log entries.\n> 4. Rename (3) to `${sha1}.ref`.\n> 5. Append `${sha1}.ref` to `stack.lock`\n> 6. Atomically rename `stack.lock` to `stack`.\n\nIn case 3.+4. becomes time consuming, it can be prepared outside\nthe lock, such that inside the lock we'd only need to check\nfor contention of refs? For example if I'd want to update one ref and\nanother write wants to update another refs, we'd both be preparing\nthe a new refstable containing one ref and log, then one of us obtains\nthe lock and writes. The second writer would then need to inspect\nthe delta of the stack and see if any ref that they want to change\nwas touched.\n\n> ### Compaction\n>\n> A partial stack of reftables can be compacted by merging references\n> using a straightforward merge join across reftables, selecting the\n> most recent value for output, and omitting deleted references that do\n> not appear in remaining, lower reftables.\n>\n> For sake of illustration, assume the stack currently consists of\n> reftable files (from oldest to newest): A, B, C, and D. The compactor\n> is going to compact B and C, leaving A and D alone.\n>\n> 1.  Obtain lock `stack.lock` and read the `stack` file.\n> 2.  Obtain locks `B.lock` and `C.lock`.\n>     Ownership of these locks prevents other processes from trying\n> to compact these files.\n> 3.  Release `stack.lock`.\n> 4.  Compact `B` and `C` in temp file `.refXXXXXXX`.\n> 5.  Reacquire lock `stack.lock`.\n> 6.  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.\n> 7.  Rename `.refXXXXXXX` to `X`.\n> 8.  Write the new stack to `stack.lock`, replacing `B` and `C` with `X`.\n> 9.  Atomically rename `stack.lock` to `stack`.\n> 10. Delete `B` and `C`, perhaps after a short sleep to avoid forcing\n>     readers to backtrack.\n>\n> This strategy permits compactions to proceed independently of updates.\n\n10. could be deferred to gc as well. auto gc would need to learn about\nthe number\nof loose refstables in that case.\n\nThanks,\nStefan\n"},{"id":"324661","messageId":"CAJo=hJuHsKY5YkmoBqCNvv2tvRdJFtD02JrnUko7iJbpSJWHgQ@mail.gmail.com","threadId":"46405","inReplyTo":"CAGZ79kaFmxRSp1YBXc=6YEeDGUO-VLBF0yk+Bb0np7x80z_Vog@mail.gmail.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-07-17T19:04:34Z","receivedAt":"2017-07-17T19:05:08Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Mon, Jul 17, 2017 at 11:53 AM, Stefan Beller <sbeller@google.com> wrote:\n> On Mon, Jul 17, 2017 at 8:01 AM, Shawn Pearce <spearce@spearce.org> wrote:\n>\n>> A ref block is written as:\n>>\n>>     'r'\n>>     uint24 ( block_len )\n>>     ref_record*\n>>     uint32( restart_offset )*\n>>     uint16( number_of_restarts )\n>>     padding?\n>>\n> ...\n>>\n>> The 2-byte `number_of_restarts + 1` stores the number of entries in\n>> the `restart_offset` list.\n>\n> This means uint16( number_of_restarts ) cannot be 0, but has to be 1\n> to indicate no restarts?\n\nA block must have at least one restart in it, the first ref_record\nmust be a restart. So number_of_restarts in the tail of the block can\nbe 0, which implies 1 restart (number_of_restarts + 1), and the first\nrestart is required at the first ref_record. :)\n\n> When starting to write a block, we need to know exactly how large\n> the ref_records* and restart offsets need to be to put the\n> number_of_restarts at the position as promised via block_len.\n> This sounds complicated unless I missed the obvious.\n\nCorrect. The writer needs to compute the block size before it writes\nthe block. It does so by buffering the block contents until its\napproximately full, then fixes block_len, and flushes the block.\n\n> Going by this, would it rather make sense to omit the block_len\n> and then scan backwards from *block_size-1 to find the first non-NUL\n> and that will be the number_of_restarts?\n\nNot quite. On small reftable files the \"physical\" block may be shared\nwith a log block ('g'). We need to be able to reliably find the of the\nref block ('r'), without padding between the two blocks.\n\n> Or we could allow additional padding between ref_record and\n> restart_offsets, such that the writer implementation has wiggle room\n> for the restarting logic.\n\nI had that in an older format description, and removed it. Placing the\npadding at the end of the block was simpler for the reader and writer\nimplementation to handle.\n\n\n>> Log record keys are structured as:\n>>\n>>     ref_name '\\0' reverse_int32( time_sec )\n>>\n>> where `time_sec` is the update time in seconds since the epoch.\n>\n> The epoch ends 2038, which is in 21 years. (Did you just volunteer\n> to fixup the time issues in 20 years?)\n> If possible I'd prefer a date to be encoded with more range available.\n\nGood point. However, I think in 20 years we'll see 2 more hash\nfunctions for Git, and we can bump reftable to v2 and expand the field\nto 8 bytes.\n\n> The ref names itself are compressed, would we also want to compress\n> the timing information?\n\nThe time field is also prefix compressed as part of the ref name's\nprefix compression. So there is no need to move to the complexity of a\nvarint or anything else.\n\n\n>> ### Update transactions\n>>\n>> Although reftables are immutable, mutations are supported by writing a\n>> new reftable and atomically appending it to the stack:\n>>\n>> 1. Atomically create `stack.lock`\n>> 2. Copy current stack to `stack.lock`.\n>> 3. Prepare new reftable in temp file `.refXXXXXXX`.\n>>    Include log entries.\n>> 4. Rename (3) to `${sha1}.ref`.\n>> 5. Append `${sha1}.ref` to `stack.lock`\n>> 6. Atomically rename `stack.lock` to `stack`.\n>\n> In case 3.+4. becomes time consuming, it can be prepared outside\n> the lock, such that inside the lock we'd only need to check\n> for contention of refs? For example if I'd want to update one ref and\n> another write wants to update another refs, we'd both be preparing\n> the a new refstable containing one ref and log, then one of us obtains\n> the lock and writes. The second writer would then need to inspect\n> the delta of the stack and see if any ref that they want to change\n> was touched.\n\nExcellent point, it reduces the contention window for non-conflicting\nwrites. I will update this section with your input, thank you Stefan.\n"},{"id":"324666","messageId":"xmqqlgnmhmep.fsf@gitster.mtv.corp.google.com","threadId":"46405","inReplyTo":"CAJo=hJtTp2eA3z9wW9cHo-nA7kK40vVThqh6inXpbCcqfdMP9g@mail.gmail.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2017-07-17T19:51:42Z","receivedAt":"2017-07-17T19:51:50Z","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> This is an updated draft after discussion on list with Peff, Michael\n> Haggerty, and Dave Borowitz.\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> Biggest changes from the first proposal are:\n>\n> - reflog is now integrated into reftable\n> - block headers slightly different\n> - Peff's stack management idea is used\n> - Michael's compaction idea is used\n\nJust a few comments.\n\n> A variable number of 4-byte `restart_offset` values follows the\n> records.  Offsets are relative to the start of the block (0 in first\n> block to include file header) and refer to the first byte of any\n> `ref_record` whose name has not been prefixed compressed.  Readers can\n> start linear scans from any of these records.\n\nIt is unclear what \"0 in first block to include file header\" wants\nto say.  Do I write \"8\" if I want to express the offset of the first\nrecord in the first block, or do I write \"0\"?\n\n> The 2-byte `number_of_restarts + 1` stores the number of entries in\n> the `restart_offset` list.\n\nIt is unclear whose responsibility it is to add this \"1\".  Does this\nmean a reader thinks there is one entry in the restart table when it\nsees \"0\" in the number_of_restarts field (hence you can have max\n65536 entries in total)?\n\n> Readers can use the restart count to binary search between restarts\n> before starting a linear scan.  The `number_of_restarts` field must be\n> the last 2 bytes of the block as specified by `block_len` from the\n> block header.\n\nDoes the new term \"restart count\" mean the same thing as\nnumber_of_restarts?\n\n> ### Log block format\n>\n> A log block is written as:\n>\n>     'g'\n>     uint24( block_len )\n>     zlib_deflate {\n>       log_record*\n>       int32( restart_offset )*\n>       int16( number_of_restarts )\n>     }\n>\n> Log blocks look similar to ref blocks, except `block_type = 'g'`.\n\nIs there a general recommended strategy for writers to choose how\nmany entries to include in a single physical block?  I understand\nthat the deflated whole must fit in the physical block whose length\nis defined in the footer of the whole file, and in general you would\nnot know how small the data deflates down to before compressing,\nright?\n\n> Log record keys are structured as:\n>\n>     ref_name '\\0' reverse_int32( time_sec )\n>\n> where `time_sec` is the update time in seconds since the epoch.  The\n> `reverse_int32` function inverses the value so lexographical ordering\n> the network byte order time sorts more recent records first:\n>\n>     reverse_int(int32 t) {\n>       return 0xffffffff - t;\n>     }\n\nIs 2038 an issue, or by that time we'd all be retired together with\nthis file format and it won't be our problem?\n\nAs the file format uses delta compression with restarts, a reader\nneeds to sequencially scan some bounded number of entries to get the\ncontents of a specific entry anyway, so I am wondering if it is\nworth storing a longer timestamp in varint() for an restart entry\nand express the timestamp on delta entries as difference to the\nprevious entry.\n\n> ### Log index\n>\n> The log index stores the log key (`refname \\0 reverse_int32(time_sec)`)\n> for the last log record of every log block in the file, supporting\n> bounded-time lookup.\n\nThis assumes that timestamps never wildly rewind in the reflog,\ndoesn't it?  Is that a sensible assumption?\n\nOr does \"the last log record\" in the above mean \"the log record with\nlargest timestamp?  ... ah, not that is still not sufficient.  You'd\nstill need to assume that timestamps on entries in one log block must\nbe all older than the ones on entries in later log blocks.  Hmph...\n\nAlso it is not clear to me how reflogs for two refs would be\nintermixed in the log blocks, and what log keys for the entries must\nbe recorded in the log index, to facilitate efficient lookup.  Is it\nassumed that a consecutive sequence of log blocks record reflogs for\nthe same ref, before the sequence of log blocks switch to record\nreflogs for another ref, or something?\n\n> A log index block must be written if 2 or more log blocks are written\n> to the file.  If present, the log index appears after the first log\n> block.  There is no padding used to align the log index to block\n> alignment.\n>\n> Log index format is identical to ref index, except the keys are 5\n> bytes longer to include `'\\0'` and the 4-byte `reverse_int32(time)`.\n> Records use `block_offset` to refer to the start of a log block.\n\nI am assuming that we do not care about being able to quickly\ndetermine master@{24028}; I would imagine that it wouldn't be too\nhard to add an index to help such query, but I offhand would not\nknow the details until I figure out how the format handles reflog\nentries for multiple refs first.\n"},{"id":"324667","messageId":"CAGZ79kb-+NhP7E_=mXEEQJPQjYkU18gP8OkuMOS08aD+xbeMgg@mail.gmail.com","threadId":"46405","inReplyTo":"CAJo=hJuHsKY5YkmoBqCNvv2tvRdJFtD02JrnUko7iJbpSJWHgQ@mail.gmail.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Stefan Beller","fromEmail":"sbeller@google.com","sentAt":"2017-07-17T19:56:36Z","receivedAt":"2017-07-17T19:56:42Z","isPatch":false,"sender":{"key":"stefanbeller@gmail.com","avatar":"https://avatars.githubusercontent.com/u/455868?v=4"},"body":"On Mon, Jul 17, 2017 at 12:04 PM, Shawn Pearce <spearce@spearce.org> wrote:\n\n> A block must have at least one restart in it, the first ref_record\n> must be a restart. So number_of_restarts in the tail of the block can\n> be 0, which implies 1 restart (number_of_restarts + 1), and the first\n> restart is required at the first ref_record. :)\n\nHah! I assumed the first entry to not be recorded because it is always\na restart by definition of the file format, so it could be omitted in the\nrestart_offset list, but that would complicate the implementation, such\nthat including it makes sense.\n\n>\n>> When starting to write a block, we need to know exactly how large\n>> the ref_records* and restart offsets need to be to put the\n>> number_of_restarts at the position as promised via block_len.\n>> This sounds complicated unless I missed the obvious.\n>\n> Correct. The writer needs to compute the block size before it writes\n> the block. It does so by buffering the block contents until its\n> approximately full, then fixes block_len, and flushes the block.\n\nSo that is another trade off for determining the block size. \"How much\ncan I buffer?\"\n\n>> Going by this, would it rather make sense to omit the block_len\n>> and then scan backwards from *block_size-1 to find the first non-NUL\n>> and that will be the number_of_restarts?\n>\n> Not quite. On small reftable files the \"physical\" block may be shared\n> with a log block ('g'). We need to be able to reliably find the of the\n> ref block ('r'), without padding between the two blocks.\n\nI'd need to reread the proposal to understand this bit as I assumed that\neach block starts at a multiple of block_size. However we could choose\nblock_size such that there is no padding between 'r' and 'g'. Ok,\nmakes sense.\n\n> The time field is also prefix compressed as part of the ref name's\n> prefix compression. So there is no need to move to the complexity of a\n> varint or anything else.\n\nI agree, that is why you explicitly said that the key is\n    ref_name '\\0' reverse_int32( time_sec )\n\nNote (as found out in discussion with jrnieder@): The size of the integer\nis determined by the suffix length encoding and the preceding '\\0',\nsuch that the file format allows arbitrary integer size. So instead of\npretending we can only do 32 bit here, just say 'uint' ?\n"},{"id":"324744","messageId":"CAJo=hJuP9GdudFsA_ToFQwx-zESaDHRDXHLxmvAXSX5CKmh7JQ@mail.gmail.com","threadId":"46405","inReplyTo":"xmqqlgnmhmep.fsf@gitster.mtv.corp.google.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-07-18T20:54:18Z","receivedAt":"2017-07-18T20:54:45Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"On Mon, Jul 17, 2017 at 12:51 PM, Junio C Hamano <gitster@pobox.com> wrote:\n> Shawn Pearce <spearce@spearce.org> writes:\n>> You can read a rendered version of this here:\n>> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md\n>\n> Just a few comments.\n>\n>> A variable number of 4-byte `restart_offset` values follows the\n>> records.  Offsets are relative to the start of the block (0 in first\n>> block to include file header) and refer to the first byte of any\n>> `ref_record` whose name has not been prefixed compressed.  Readers can\n>> start linear scans from any of these records.\n>\n> It is unclear what \"0 in first block to include file header\" wants\n> to say.  Do I write \"8\" if I want to express the offset of the first\n> record in the first block, or do I write \"0\"?\n\n\"8\". I've updated the text to try and clarify this better.\n\n\n>> The 2-byte `number_of_restarts + 1` stores the number of entries in\n>> the `restart_offset` list.\n>\n> It is unclear whose responsibility it is to add this \"1\".  Does this\n> mean a reader thinks there is one entry in the restart table when it\n> sees \"0\" in the number_of_restarts field (hence you can have max\n> 65536 entries in total)?\n\nCorrect, I've reworded this section to clarify the reader must add +1\nto reach the potential max of 65536 entries in total.\n\n>> Readers can use the restart count to binary search between restarts\n>> before starting a linear scan.  The `number_of_restarts` field must be\n>> the last 2 bytes of the block as specified by `block_len` from the\n>> block header.\n>\n> Does the new term \"restart count\" mean the same thing as\n> number_of_restarts?\n\nNot quite (because of the +1 issue), I've fixed the document to\nintroduce and define restart_count.\n\n\n>> ### Log block format\n>>\n>> A log block is written as:\n>>\n>>     'g'\n>>     uint24( block_len )\n>>     zlib_deflate {\n>>       log_record*\n>>       int32( restart_offset )*\n>>       int16( number_of_restarts )\n>>     }\n>>\n>> Log blocks look similar to ref blocks, except `block_type = 'g'`.\n>\n> Is there a general recommended strategy for writers to choose how\n> many entries to include in a single physical block?  I understand\n> that the deflated whole must fit in the physical block whose length\n> is defined in the footer of the whole file, and in general you would\n> not know how small the data deflates down to before compressing,\n> right?\n\nNo, this is an  incorrect understanding. The deflated log blocks do\nnot match the physical block length of the file. They are variable\nlength, matching whatever the deflater output, with no inter-block\npadding.\n\nWriters should allocate a \"reasonable buffer\" (my prototype has it\ndefault to 2x the ref block length), pack log records into that, then\ndeflate that when its at capacity.\n\n\n>> Log record keys are structured as:\n>>\n>>     ref_name '\\0' reverse_int32( time_sec )\n>>\n>> where `time_sec` is the update time in seconds since the epoch.  The\n>> `reverse_int32` function inverses the value so lexographical ordering\n>> the network byte order time sorts more recent records first:\n>>\n>>     reverse_int(int32 t) {\n>>       return 0xffffffff - t;\n>>     }\n>\n> Is 2038 an issue, or by that time we'd all be retired together with\n> this file format and it won't be our problem?\n\nBased on discussion with Michael Haggerty, this is now an 8 byte field\nstoring microseconds since the epoch. We should be good through year\n9999.\n\n\n>> ### Log index\n>>\n>> The log index stores the log key (`refname \\0 reverse_int32(time_sec)`)\n>> for the last log record of every log block in the file, supporting\n>> bounded-time lookup.\n>\n> This assumes that timestamps never wildly rewind in the reflog,\n> doesn't it?  Is that a sensible assumption?\n\nOy. I forgot that local clock skew can cause this sort of behavior. :(\n\n> Or does \"the last log record\" in the above mean \"the log record with\n> largest timestamp?  ... ah, not that is still not sufficient.  You'd\n> still need to assume that timestamps on entries in one log block must\n> be all older than the ones on entries in later log blocks.  Hmph...\n\nCorrect; I was assuming the times would be in order.\n\n> Also it is not clear to me how reflogs for two refs would be\n> intermixed in the log blocks, and what log keys for the entries must\n> be recorded in the log index, to facilitate efficient lookup.  Is it\n> assumed that a consecutive sequence of log blocks record reflogs for\n> the same ref, before the sequence of log blocks switch to record\n> reflogs for another ref, or something?\n\nMultiple refs share the same log block.\n\n>> A log index block must be written if 2 or more log blocks are written\n>> to the file.  If present, the log index appears after the first log\n>> block.  There is no padding used to align the log index to block\n>> alignment.\n>>\n>> Log index format is identical to ref index, except the keys are 5\n>> bytes longer to include `'\\0'` and the 4-byte `reverse_int32(time)`.\n>> Records use `block_offset` to refer to the start of a log block.\n>\n> I am assuming that we do not care about being able to quickly\n> determine master@{24028}; I would imagine that it wouldn't be too\n> hard to add an index to help such query, but I offhand would not\n> know the details until I figure out how the format handles reflog\n> entries for multiple refs first.\n\nThere is no assistance for master@{24028} quickly, its just a brute\nforce scan through 24,028 log records that pertain to master. Roughly\nthe same as the current reflog format.\n"},{"id":"324763","messageId":"87k234tti7.fsf@gmail.com","threadId":"46405","inReplyTo":"CAJo=hJuP9GdudFsA_ToFQwx-zESaDHRDXHLxmvAXSX5CKmh7JQ@mail.gmail.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Ævar Arnfjörð Bjarmason","fromEmail":"avarab@gmail.com","sentAt":"2017-07-19T14:02:08Z","receivedAt":"2017-07-19T14:10:29Z","isPatch":false,"sender":{"key":"avarab@gmail.com","avatar":"https://avatars.githubusercontent.com/u/45301?v=4"},"body":"\nOn Tue, Jul 18 2017, Shawn Pearce jotted:\n\n> On Mon, Jul 17, 2017 at 12:51 PM, Junio C Hamano <gitster@pobox.com> wrote:\n>> Shawn Pearce <spearce@spearce.org> writes:\n>>> where `time_sec` is the update time in seconds since the epoch.  The\n>>> `reverse_int32` function inverses the value so lexographical ordering\n>>> the network byte order time sorts more recent records first:\n>>>\n>>>     reverse_int(int32 t) {\n>>>       return 0xffffffff - t;\n>>>     }\n>>\n>> Is 2038 an issue, or by that time we'd all be retired together with\n>> this file format and it won't be our problem?\n>\n> Based on discussion with Michael Haggerty, this is now an 8 byte field\n> storing microseconds since the epoch. We should be good through year\n> 9999.\n\nI think this should be s/microseconds/nanoseconds/, not because there's\nsome great need to get better resolution than nanoseconds, but because:\n\n a) We already have WIP code (bp/fsmonitor) that's storing 64 bit\n    nanoseconds since the epoch, albeit for the index, not for refs.\n\n b) There are several filesystems that have nanosecond resolution now,\n    and it's likely more will start using that.\n\nThus:\n\n x) If you use such a filesystem you'll lose time resolution with this\n    ref backend v.s. storing them on disk, which isn't itself a big\n    deal, but more importantly you lose 1=1 time mapping as you\n    transition and convert between the two.\n\n y) Our own code will need to juggle second resolution epochs\n    (traditional FSs, any 32bit epoch format), microseconds (this\n    proposal), and nanoseconds (new FSs, bp/fsmonitor) internally in\n    various places.\n\n    Let's not make this harder than it needs to be and just settle on\n    two epoch resolution formats if we can help it, and so far it looks\n    like we can.\n\nThe downside is that instead of lasting through the year 9999 the 64 bit\nnanosecond resolution is only good up until the year 2554, which I think\nis an acceptable trade-off given the above.\n"},{"id":"324920","messageId":"CAJo=hJtCL6ZH2DPgCAkQptouM0xSbSnfwMX-f+RM=1wCucay9g@mail.gmail.com","threadId":"46405","inReplyTo":"87k234tti7.fsf@gmail.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Shawn Pearce","fromEmail":"spearce@spearce.org","sentAt":"2017-07-23T21:46:57Z","receivedAt":"2017-07-23T21:47:30Z","isPatch":false,"sender":{"key":"spearce@spearce.org","avatar":"https://avatars.githubusercontent.com/u/34844?v=4"},"body":"My apologies for not responding to this piece of feedback earlier.\n\nOn Wed, Jul 19, 2017 at 7:02 AM, Ævar Arnfjörð Bjarmason\n<avarab@gmail.com> wrote:\n> On Tue, Jul 18 2017, Shawn Pearce jotted:\n>> On Mon, Jul 17, 2017 at 12:51 PM, Junio C Hamano <gitster@pobox.com> wrote:\n>>> Shawn Pearce <spearce@spearce.org> writes:\n>>>> where `time_sec` is the update time in seconds since the epoch.  The\n>>>> `reverse_int32` function inverses the value so lexographical ordering\n>>>> the network byte order time sorts more recent records first:\n>>>>\n>>>>     reverse_int(int32 t) {\n>>>>       return 0xffffffff - t;\n>>>>     }\n>>>\n>>> Is 2038 an issue, or by that time we'd all be retired together with\n>>> this file format and it won't be our problem?\n>>\n>> Based on discussion with Michael Haggerty, this is now an 8 byte field\n>> storing microseconds since the epoch. We should be good through year\n>> 9999.\n>\n> I think this should be s/microseconds/nanoseconds/, not because there's\n> some great need to get better resolution than nanoseconds, but because:\n>\n>  a) We already have WIP code (bp/fsmonitor) that's storing 64 bit\n>     nanoseconds since the epoch, albeit for the index, not for refs.\n>\n>  b) There are several filesystems that have nanosecond resolution now,\n>     and it's likely more will start using that.\n\nThe time in a reflog and the time returned by lstat(2) to detect dirty\nfiles in the working tree are unrelated. Of course we want the\ndircache to be reflecting the highest precision available from lstat,\nto reduce the number of files that must be content hashed for racily\nclean detection. So if a filesystem is using nanoseconds, dircache\nmaybe should support it.\n\n> Thus:\n>\n>  x) If you use such a filesystem you'll lose time resolution with this\n>     ref backend v.s. storing them on disk, which isn't itself a big\n>     deal, but more importantly you lose 1=1 time mapping as you\n>     transition and convert between the two.\n\nNo, you won't. The reflog today ($GIT_DIR/logs) is storing second\nprecision in the log record. What precision the filesystem is using as\nan mtime is irrelevant.\n\nFurther, microsecond is sufficient resolution for reflog data. From my\nbenchmarking just reading a reference from a very hot reftable costs\n~20.2 usec. Any update of a reference requires a read-compare-modify\ncycle, and so updates aren't going to be more frequent than 20 usec.\n\n>  y) Our own code will need to juggle second resolution epochs\n>     (traditional FSs, any 32bit epoch format), microseconds (this\n>     proposal), and nanoseconds (new FSs, bp/fsmonitor) internally in\n>     various places.\n\nBut these are also unrelated areas. IMHO, the nanosecond stuff should\nbe confined to the dircache management code and working tree\ncomparison code, and not be leaking out of there. Commit objects are\nstill recorded with second precision, and that isn't going to change.\n\nTherefore I decided to stick with microseconds in the reftable v3\ndraft that I posted on July 22nd.\n"},{"id":"324927","messageId":"87o9sapvfp.fsf@gmail.com","threadId":"46405","inReplyTo":"CAJo=hJtCL6ZH2DPgCAkQptouM0xSbSnfwMX-f+RM=1wCucay9g@mail.gmail.com","subject":"Re: reftable [v2]: new ref storage format","fromName":"Ævar Arnfjörð Bjarmason","fromEmail":"avarab@gmail.com","sentAt":"2017-07-23T23:47:38Z","receivedAt":"2017-07-23T23:49:20Z","isPatch":false,"sender":{"key":"avarab@gmail.com","avatar":"https://avatars.githubusercontent.com/u/45301?v=4"},"body":"\nOn Sun, Jul 23 2017, Shawn Pearce jotted:\n\n> My apologies for not responding to this piece of feedback earlier.\n>\n> On Wed, Jul 19, 2017 at 7:02 AM, Ævar Arnfjörð Bjarmason\n> <avarab@gmail.com> wrote:\n>> On Tue, Jul 18 2017, Shawn Pearce jotted:\n>>> On Mon, Jul 17, 2017 at 12:51 PM, Junio C Hamano <gitster@pobox.com> wrote:\n>>>> Shawn Pearce <spearce@spearce.org> writes:\n>>>>> where `time_sec` is the update time in seconds since the epoch.  The\n>>>>> `reverse_int32` function inverses the value so lexographical ordering\n>>>>> the network byte order time sorts more recent records first:\n>>>>>\n>>>>>     reverse_int(int32 t) {\n>>>>>       return 0xffffffff - t;\n>>>>>     }\n>>>>\n>>>> Is 2038 an issue, or by that time we'd all be retired together with\n>>>> this file format and it won't be our problem?\n>>>\n>>> Based on discussion with Michael Haggerty, this is now an 8 byte field\n>>> storing microseconds since the epoch. We should be good through year\n>>> 9999.\n>>\n>> I think this should be s/microseconds/nanoseconds/, not because there's\n>> some great need to get better resolution than nanoseconds, but because:\n>>\n>>  a) We already have WIP code (bp/fsmonitor) that's storing 64 bit\n>>     nanoseconds since the epoch, albeit for the index, not for refs.\n>>\n>>  b) There are several filesystems that have nanosecond resolution now,\n>>     and it's likely more will start using that.\n>\n> The time in a reflog and the time returned by lstat(2) to detect dirty\n> files in the working tree are unrelated. Of course we want the\n> dircache to be reflecting the highest precision available from lstat,\n> to reduce the number of files that must be content hashed for racily\n> clean detection. So if a filesystem is using nanoseconds, dircache\n> maybe should support it.\n>\n>> Thus:\n>>\n>>  x) If you use such a filesystem you'll lose time resolution with this\n>>     ref backend v.s. storing them on disk, which isn't itself a big\n>>     deal, but more importantly you lose 1=1 time mapping as you\n>>     transition and convert between the two.\n>\n> No, you won't. The reflog today ($GIT_DIR/logs) is storing second\n> precision in the log record. What precision the filesystem is using as\n> an mtime is irrelevant.\n\nTo this & the point above: Sorry about being unclear, I'm talking about\nthe mtime on the modified loose ref. This format proposes to replace\nboth loose & packed refs, does it not? The reflog time is not the only\nplace were we store the mtime of a ref. On my local ext4:\n\n    $ tail -n 1 .git/logs/refs/heads/master\n    <sha1> <sha1> Ævar Arnfjörð Bjarmason <avarab@gmail.com> 1500852355 +0200   commit: test\n    $ perl -wE 'say ~~localtime shift' 1500852355\n    Mon Jul 24 01:25:55 2017\n    $ stat -c %y .git/logs/refs/heads/master\n    2017-07-24 01:25:55.531379799 +0200\n\nOf course you lose this information as soon as you \"git pack-refs\", but\nit's there now & implicitly part of our current FS-backed on-disk\nformat.\n\nSo what I meant by \"x\" is that if to test this new reftable backend you\nwrite a \"git pack-reftable\" you won't be able to 1=1 map it to the\nmtimes you have on the fs showing when the ref was updated, but I see\nnow that you were perhaps never intending to use the more accurate FS\ntime at all for the loose refs, but just use the second resolution\nreflog data.\n\n> Further, microsecond is sufficient resolution for reflog data. From my\n> benchmarking just reading a reference from a very hot reftable costs\n> ~20.2 usec. Any update of a reference requires a read-compare-modify\n> cycle, and so updates aren't going to be more frequent than 20 usec.\n\nRight, I'm not arguing that it isn't sufficient, just that it's\nintroducing a needless variation by adding a third timestamp resolution\nto git.\n\nEven if it's not the same logical area in git (dir management v.s. ref\nmanagement) code to e.g. pretty format timestamps of sec/usec/nsec\nresolution would tend to get shared, so we'd end up with 3 variants of\nthose instead of 2.\n\nThat's of course trivial, but so would be just deciding that ~500 years\nof future proofing is good enough without any extra storage size for\nthose 64 bits and doing away with 1/3.\n\nJust standardizing that makes more sense than picking the exact right\ntime resolution for every use case IMO. Otherwise we'll come up with\nsome other thingy in the future that just needs e.g. millisecond in its\nformat, and then end up with 4 variants....\n\nI also see from \"Update transactions\" that unlike the current loose\nbackend the reftable backend wouldn't support multiple writers on\nmultiple machines (think NFS-mounted git master) updating unrelated\nrefs, which would break this usec assumption (but which holds due to the\nlocking involved in the new backend).\n\n>>  y) Our own code will need to juggle second resolution epochs\n>>     (traditional FSs, any 32bit epoch format), microseconds (this\n>>     proposal), and nanoseconds (new FSs, bp/fsmonitor) internally in\n>>     various places.\n>\n> But these are also unrelated areas. IMHO, the nanosecond stuff should\n> be confined to the dircache management code and working tree\n> comparison code, and not be leaking out of there. Commit objects are\n> still recorded with second precision, and that isn't going to change.\n>\n> Therefore I decided to stick with microseconds in the reftable v3\n> draft that I posted on July 22nd.\n"}]}