git@vger.kernel.org mailing list mirror (one of many)
 help / color / mirror / code / Atom feed
* Re: reftable [v6]: new ref storage format
@ 2017-08-07  1:47 Shawn Pearce
  2017-08-07 18:27 ` Stefan Beller
                   ` (4 more replies)
  0 siblings, 5 replies; 14+ messages in thread
From: Shawn Pearce @ 2017-08-07  1:47 UTC (permalink / raw)
  To: git, Jeff King, Michael Haggerty
  Cc: Junio C Hamano, David Borowitz, Stefan Beller

6th iteration of the reftable storage format.

You can read a rendered version of this here:
https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md

Changes from v5:
- extensions.refStorage = reftable is used to select this format.

- Log records can be explicitly deleted (for refs/stash).
- Log records may use Michael Haggerty's chained idea to compress before zlib.
  This saved ~5.8% on one of my example repositories.


# reftable

[TOC]

## Overview

### Problem statement

Some repositories contain a lot of references (e.g.  android at 866k,
rails at 31k).  The existing packed-refs format takes up a lot of
space (e.g.  62M), and does not scale with additional references.
Lookup of a single reference requires linearly scanning the file.

Atomic pushes modifying multiple references require copying the
entire packed-refs file, which can be a considerable amount of data
moved (e.g. 62M in, 62M out) for even small transactions (2 refs
modified).

Repositories with many loose references occupy a large number of disk
blocks from the local file system, as each reference is its own file
storing 41 bytes (and another file for the corresponding reflog).
This negatively affects the number of inodes available when a large
number of repositories are stored on the same filesystem.  Readers can
be penalized due to the larger number of syscalls required to traverse
and read the `$GIT_DIR/refs` directory.

### Objectives

- Near constant time lookup for any single reference, even when the
  repository is cold and not in process or kernel cache.
- Near constant time verification a SHA-1 is referred to by at least
  one reference (for allow-tip-sha1-in-want).
- Efficient lookup of an entire namespace, such as `refs/tags/`.
- Support atomic push with `O(size_of_update)` operations.
- Combine reflog storage with ref storage for small transactions.
- Separate reflog storage for base refs and historical logs.

### Description

A reftable file is a portable binary file format customized for
reference storage. References are sorted, enabling linear scans,
binary search lookup, and range scans.

Storage in the file is organized into blocks.  Prefix compression
is used within a single block to reduce disk space.  Block size is
tunable by the writer.

### Performance

Space used, packed-refs vs. reftable:

repository | packed-refs | reftable | % original | avg ref  | avg obj
-----------|------------:|---------:|-----------:|---------:|--------:
android    |      62.2 M |   34.4 M |     55.2%  | 33 bytes | 8 bytes
rails      |       1.8 M |    1.1 M |     57.7%  | 29 bytes | 6 bytes
git        |      78.7 K |   44.0 K |     60.0%  | 50 bytes | 6 bytes
git (heads)|       332 b |    274 b |     83.1%  | 34 bytes | 0 bytes

Scan (read 866k refs), by reference name lookup (single ref from 866k
refs), and by SHA-1 lookup (refs with that SHA-1, from 866k refs):

format      | cache | scan    | by name        | by SHA-1
------------|------:|--------:|---------------:|---------------:
packed-refs | cold  |  402 ms | 409,660.1 usec | 412,535.8 usec
packed-refs | hot   |         |   6,844.6 usec |  20,110.1 usec
reftable    | cold  |  112 ms |      33.9 usec |     323.2 usec
reftable    | hot   |         |      20.2 usec |     320.8 usec

Space used for 149,932 log entries for 43,061 refs,
reflog vs. reftable:

format        | size  | avg entry
--------------|------:|-----------:
$GIT_DIR/logs | 173 M | 1209 bytes
reftable      |   5 M |   37 bytes

## Details

### Peeling

References stored in a reftable are peeled, a record for an annotated
(or signed) tag records both the tag object, and the object it refers
to.

### Reference name encoding

Reference names are an uninterpreted sequence of bytes that must pass
[git-check-ref-format][ref-fmt] as a valid reference name.

[ref-fmt]: https://git-scm.com/docs/git-check-ref-format

### Network byte order

All multi-byte, fixed width fields are in network byte order.

### Ordering

Blocks are lexicographically ordered by their first reference.

### Directory/file conflicts

The reftable format accepts both `refs/heads/foo` and
`refs/heads/foo/bar` as distinct references.

This property is useful for retaining log records in reftable, but may
confuse versions of Git using `$GIT_DIR/refs` directory tree to
maintain references.  Users of reftable may choose to continue to
reject `foo` and `foo/bar` type conflicts to prevent problems for
peers.

## File format

### Structure

A reftable file has the following high-level structure:

    first_block {
      header
      first_ref_block
    }
    ref_blocks*
    ref_index?
    obj_blocks*
    obj_index?
    log_blocks*
    log_index?
    footer

A log-only file omits the `ref_blocks`, `ref_index`, `obj_blocks` and
`obj_index` sections, containing only the file header and log blocks:

    first_block {
      header
    }
    log_blocks*
    log_index?
    footer

in a log-only file the first log block immediately follows the file
header, without padding to block alignment.

### Block size

The `block_size` is arbitrarily determined by the writer, and does not
have to be a power of 2.  The block size must be larger than the
longest reference name or log entry used in the repository, as
references cannot span blocks.

Powers of two that are friendly to the virtual memory system or
filesystem (such as 4k or 8k) are recommended.  Larger sizes (64k) can
yield better compression, with a possible increased cost incurred by
readers during access.

The largest block size is `16777215` bytes (15.99 MiB).

### Header

A 24-byte header appears at the beginning of the file:

    'REFT'
    uint8( version_number = 1 )
    uint24( block_size )
    uint64( min_update_index )
    uint64( max_update_index )

The `min_update_index` and `max_update_index` describe bounds for the
`update_index` field of all log records in this file.  When reftables
are used in a stack for transactions (see below), these fields can
order the files such that the prior file's `max_update_index + 1` is
the next file's `min_update_index`.

### First ref block

The first ref block shares the same block as the file header, and is
24 bytes smaller than all other blocks in the file.  The first block
immediately begins after the file header, at position 24.

If the first block is a log block (a log-only file), its block header
begins immediately at position 24.

### Ref block format

A ref block is written as:

    'r'
    uint24( block_len )
    uint16( restart_count )
    uint24( restart_offset )+
    ref_record+
    padding?

Blocks begin with `block_type = 'r'` and a 3-byte `block_len` which
encodes the number of bytes in the block up to, but not including the
optional `padding`.  This is almost always shorter than the file's
`block_size`.  In the first ref block, `block_len` includes 24 bytes
for the file header.

The 2-byte `restart_count` stores the number of entries in the
`restart_offset` list, which must not be empty.  Readers can use
`restart_count` to binary search between restarts before starting a
linear scan.

A variable number of 3-byte `restart_offset` follows.  Offsets are
relative to the start of the block and refer to the first byte of any
`ref_record` whose name has not been prefix compressed.  Entries in
the `restart_offset` list must be sorted, ascending.  Readers can
start linear scans from any of these records.

A variable number of `ref_record` fill the remainder of the block,
describing reference names and values.  The format is described below.

As the first ref block shares the first file block with the file
header, all `restart_offset` in the first block are relative to the
start of the file (position 0), and include the file header.

The end of the block may be filled with `padding` NUL bytes to fill
out the block to the common `block_size` as specified in the file
header.  Padding may be necessary to ensure the following block starts
at a block alignment, and does not spill into the tail of this block.
Padding may be omitted if the block is the last block of the file, and
there is no index block.  This allows reftable to efficiently scale
down to a small number of refs.

#### ref record

A `ref_record` describes a single reference, storing both the name and
its value(s). Records are formatted as:

    varint( prefix_length )
    varint( (suffix_length << 3) | value_type )
    suffix
    value?

The `prefix_length` field specifies how many leading bytes of the
prior reference record's name should be copied to obtain this
reference's name.  This must be 0 for the first reference in any
block, and also must be 0 for any `ref_record` whose offset is listed
in the `restart_offset` table at the end of the block.

Recovering a reference name from any `ref_record` is a simple concat:

    this_name = prior_name[0..prefix_length] + suffix

The `suffix_length` value provides the number of bytes to copy from
`suffix` to complete the reference name.

The `value` follows.  Its format is determined by `value_type`, one of
the following:

- `0x0`: deletion; no value data (see transactions, below)
- `0x1`: one 20-byte object id; value of the ref
- `0x2`: two 20-byte object ids; value of the ref, peeled target
- `0x3`: symref and text: `varint( text_len ) text`

Symbolic references use `0x3` with a `text` string starting with `"ref: "`,
followed by the complete name of the reference target.  No
compression is applied to the target name.  Other types of contents
that are also reference like, such as `FETCH_HEAD` and `MERGE_HEAD`,
may also be stored using type `0x3`.

Types `0x4..0x7` are reserved for future use.

### Ref index

The ref index stores the name of the last reference from every ref
block in the file, enabling reduced disk seeks for lookups.  Any
reference can be found by searching the index, identifying the
containing block, and searching within that block.

The index may be organized into a multi-level index, where the 1st
level index block points to additional ref index blocks (2nd level),
which may in turn point to either index blocks (3rd level) or ref
blocks (leaf level).  Disk reads required to access a ref go up with
higher index levels.  To acheive constant O(1) disk seeks for lookups
the index must be a single level, which is permitted to exceed the
file's configured `block_size`.

If present, the ref index block(s) appears after the last ref block.
The prior ref block should be padded to ensure the ref index starts on
a block alignment.

If there are at least 4 ref blocks, a ref index block should be
written to improve lookup times.  Cold reads using the index requires
2 disk reads (read index, read block), and binary searching < 4 blocks
also requires <= 2 reads.  Omitting the index block from smaller files
saves space.

Index block format:

    uint32( (1 << 31) | block_len )
    uint16( restart_count )
    uint24( restart_offset )+
    index_record+
    padding?

The index block header starts with the high bit set.  This identifies
the block as an index block, and not as a ref block, log block or file
footer.  The `block_len` field in an index block is 31-bits network
byte order, and allowed to occupy space normally used by the block
type in other blocks.  This supports single-level indexes
significantly larger than the file's `block_size`, up to 1.9 GiB.

The `restart_offset` and `restart_count` fields are identical in
format, meaning and usage as in ref blocks.

To reduce the number of reads required for random access in very large
files the index block may be larger than the other blocks.  However,
readers must hold the entire index in memory to benefit from this, so
it's a time-space tradeoff in both file size and reader memory.

Increasing the file's `block_size` decreases the index size.
Alternatively a multi-level index may be used, keeping index blocks
within the file's `block_size`, but increasing the number of blocks
that need to be accessed.

When object blocks are present the ref index block is padded with
`padding` to maintain alignment for the next block. No padding is
necessary if log blocks or the file trailer follows the ref index.

#### index record

An index record describes the last entry in another block.
Index records are written as:

    varint( prefix_length )
    varint( (suffix_length << 3) | 0 )
    suffix
    varint( block_position )

Index records use prefix compression exactly like `ref_record`.

Index records store `block_position` after the suffix, specifying the
absolute position in bytes (from the start of the file) of the block
that ends with this reference. Readers can seek to `block_position` to
begin reading the block header.

Readers must examine the block header at `block_position` to determine
if the next block is another level index block, or the leaf-level ref
block.

#### Reading the index

Readers loading the ref index must first read the footer (below) to
obtain `ref_index_position`. If not present, the position will be 0.
The `ref_index_position` address is for the 1st level root of the ref
index.

### Obj block format

Object blocks use unique, abbreviated 2-20 byte SHA-1 keys, mapping
to ref blocks containing references pointing to that object directly,
or as the peeled value of an annotated tag.  Like ref blocks, object
blocks use the file's standard `block_size`. The abbrevation length is
available in the footer as `obj_id_len`.

To save space in small files, object blocks may be omitted if the ref
index is not present, as brute force search will only need to read a
few ref blocks.  When missing, readers should brute force a linear
search of all references to lookup by SHA-1.

An object block is written as:

    'o'
    uint24( block_len )
    uint16( restart_count )
    uint24( restart_offset )+
    obj_record+
    padding?

Fields are identical to ref block.  Binary search using the restart
table works the same as in reference blocks.

Because object identifiers are abbreviated by writers to the shortest
unique abbreviation within the reftable, obj key lengths are variable
between 2 and 20 bytes.  Readers must compare only for common prefix
match within an obj block or obj index.

Object blocks should be block aligned, according to `block_size` from
the file header.  The `padding` field is filled with NULs to maintain
alignment for the next block.

#### obj record

An `obj_record` describes a single object abbreviation, and the blocks
containing references using that unique abbreviation:

    varint( prefix_length )
    varint( (suffix_length << 3) | cnt_3 )
    suffix
    varint( cnt_large )?
    varint( block_delta )*

Like in reference blocks, abbreviations are prefix compressed within
an obj block.  On large reftables with many unique objects, higher
block sizes (64k), and higher restart interval (128), a
`prefix_length` of 2 or 3 and `suffix_length` of 3 may be common in
obj records (unique abbreviation of 5-6 raw bytes, 10-12 hex digits).

Each record contains `block_count` number of block identifiers for ref
blocks.  For 1-7 blocks the block count is stored in `cnt_3`.  When
`cnt_3 = 0` the actual block count follows in a varint, `cnt_large`.

The use of `cnt_3` bets most objects are pointed to by only a single
reference, some may be pointed to be a couple of references, and very
few (if any) are pointed to by more than 7 references.

A special case exists when `cnt_3 = 0` and `cnt_large = 0`: there
are no `block_delta`, but at least one reference starts with this
abbreviation.  A reader that needs exact reference names must scan all
references to find which specific references have the desired object.
Writers should use this format when the `block_delta` list would have
overflowed the file's `block_size` due to a high number of references
pointing to the same object.

The first `block_delta` is the absolute block identifier counting from
the start of the file.  The position of that block can be obtained by
`block_delta[0] * block_size`.  Additional `block_delta` entries are
sorted ascending and relative to the prior entry, e.g.  a reader would
perform:

    block_id = block_delta[0]
    prior = block_id
    for (j = 1; j < block_count; j++) {
      block_id = prior + block_delta[j]
      prior = block_id
    }

With a `block_id` in hand, a reader must linearly scan the ref block
at `block_id * block_size` position in the file, starting from the first
`ref_record`, testing each reference's SHA-1s (for `value_type = 0x1`
or `0x2`) for full equality.  Faster searching by SHA-1 within a
single ref block is not supported by the reftable format.  Smaller
block sizes reduces the number of candidates this step must consider.

### Obj index

The obj index stores the abbreviation from the last entry for every
obj block in the file, enabling reduced disk seeks for all lookups.
It is formatted exactly the same as the ref index, but refers to obj
blocks.

The obj index should be present if obj blocks are present, as
obj blocks should only be written in larger files.

The obj index should be block aligned, according to `block_size` from
the file header.  This requires padding the last obj block to maintain
alignment.

Readers loading the obj index must first read the footer (below) to
obtain `obj_index_position`.  If not present, the position will be 0.

### Log block format

Unlike ref and obj blocks, log block sizes are variable in size, and
do not match the `block_size` specified in the file header or footer.
Writers should choose an appropriate buffer size to prepare a log block
for deflation, such as `2 * block_size`.

A log block is written as:

    'g'
    uint24( block_len )
    zlib_deflate {
      uint16( restart_count )
      uint24( restart_offset )+
      log_record+
    }

Log blocks look similar to ref blocks, except `block_type = 'g'`.

The 4-byte block header is followed by the deflated block contents
using zlib deflate.  The `block_len` in the header is the inflated
size (including 4-byte block header), and should be used by readers to
preallocate the inflation output buffer.  A log block's `block_len`
may exceed the file's `block_size`.

Offsets within the log block (e.g.  `restart_offset`) still include
the 4-byte header.  Readers may prefer prefixing the inflation output
buffer with the 4-byte header.

Within the deflate container, a variable number of `log_record`
describe reference changes.  The log record format is described
below.  See ref block format (above) for a description of
`restart_offset` and `restart_count`.

Unlike ref blocks, log blocks are written at any alignment, without
padding.  The first log block immediately follows the end of the prior
block, which omits its trailing padding.  In very small files the log
block may appear in the first block.

Because log blocks have no alignment or padding between blocks,
readers must keep track of the bytes consumed by the inflater to
know where the next log block begins.

#### log record

Log record keys are structured as:

    ref_name '\0' reverse_int64( update_index )

where `update_index` is the unique transaction identifier.  The
`update_index` field must be unique within the scope of a `ref_name`.
See the update index section below for further details.

The `reverse_int64` function inverses the value so lexographical
ordering the network byte order encoding sorts the more recent records
with higher `update_index` values first:

    reverse_int64(int64 t) {
      return 0xffffffffffffffff - t;
    }

Log records have a similar starting structure to ref and index
records, utilizing the same prefix compression scheme applied to the
log record key described above.

```
    varint( prefix_length )
    varint( (suffix_length << 3) | log_type )
    suffix
    ( log_data | log_chained )?


    log_data {
      old_id
      new_id
      varint( time_seconds )
      sint16( tz_offset )
      varint( name_length    )  name
      varint( email_length   )  email
      varint( message_length )  message
    }

    log_chained {
      old_id
      varint( time_seconds )
      not_same_committer {
        sint16( tz_offset )
        varint( name_length    )  name
        varint( email_length   )  email
      }?
      not_same_message {
        varint( message_length )  message
      }?
    }
```

Log record entries use `log_type` to indicate what follows:

- `0x0`: deletion; no log data.
- `0x1`: standard git reflog data using `log_data` above.
- `0x2..0x3`: reserved for future use.
- `0x4..0x7`: `log_chained`, with conditional members.

The `log_type = 0x0` is mostly useful for `git stash drop`, removing
an entry from the reflog of `refs/stash` in a transaction file
(below), without needing to rewrite larger files.  Readers reading a
stack of reflogs must treat this as a deletion.

For `log_type = 0x1`, the `log_data` section follows
[git update-ref][update-ref] logging, and includes:

- two 20-byte SHA-1s (old id, new id)
- varint time in seconds since epoch (Jan 1, 1970)
- 2-byte timezone offset in minutes (signed)
- varint string of committer's name
- varint string of committer's email
- varint string of message

`tz_offset` is the absolute number of minutes from GMT the committer
was at the time of the update.  For example `GMT-0800` is encoded in
reftable as `sint16(-480)` and `GMT+0230` is `sint16(150)`.

The committer email does not contain `<` or `>`, its the value
normally found between the `<>` in a git commit object header.

The `message_length` may be 0, in which case there was no message
supplied for the update.

For `log_type = 0x4..0x7` the `log_chained` section is used instead to
compress information that already appeared in a prior log record.  The
`log_chained` always includes `old_id` for this record, as `new_id` is
implied by the prior (by file order, more recent) record's `old_id`.

The `not_same_committer` block appears if `log_type & 0x1` is true,
`not_same_message` block appears if `log_type & 0x2` is true.  When
one of these blocks is missing, its values are implied by the prior
(more recent) log record.

[update-ref]: https://git-scm.com/docs/git-update-ref#_logging_updates

#### Reading the log

Readers accessing the log must first read the footer (below) to
determine the `log_position`.  The first block of the log begins at
`log_position` bytes since the start of the file.  The `log_position`
is not block aligned.

#### Importing logs

When importing from `$GIT_DIR/logs` writers should globally order all
log records roughly by timestamp while preserving file order, and
assign unique, increasing `update_index` values for each log line.
Newer log records get higher `update_index` values.

Although an import may write only a single reftable file, the reftable
file must span many unique `update_index`, as each log line requires
its own `update_index` to preserve semantics.

### Log index

The log index stores the log key (`refname \0 reverse_int64(update_index)`)
for the last log record of every log block in the file, supporting
bounded-time lookup.

A log index block must be written if 2 or more log blocks are written
to the file.  If present, the log index appears after the last log
block.  There is no padding used to align the log index to block
alignment.

Log index format is identical to ref index, except the keys are 9
bytes longer to include `'\0'` and the 8-byte
`reverse_int64(update_index)`.  Records use `block_position` to
refer to the start of a log block.

#### Reading the index

Readers loading the log index must first read the footer (below) to
obtain `log_index_position`. If not present, the position will be 0.

### Footer

After the last block of the file, a file footer is written.  It begins
like the file header, but is extended with additional data.

A 68-byte footer appears at the end:

```
    'REFT'
    uint8( version_number = 1 )
    uint24( block_size )
    uint64( min_update_index )
    uint64( max_update_index )

    uint64( ref_index_position )
    uint64( (obj_position << 5) | obj_id_len )
    uint64( obj_index_position )

    uint64( log_position )
    uint64( log_index_position )

    uint32( CRC-32 of above )
```

If a section is missing (e.g. ref index) the corresponding position
field (e.g. `ref_index_position`) will be 0.

- `obj_position`: byte position for the first obj block.
- `obj_id_len`: number of bytes used to abbreviate object identifiers
  in obj blocks.
- `log_position`: byte position for the first log block.
- `ref_index_position`: byte position for the start of the ref index.
- `obj_index_position`: byte position for the start of the obj index.
- `log_index_position`: byte position for the start of the log index.

#### Reading the footer

Readers must seek to `file_length - 68` to access the footer.  A
trusted external source (such as `stat(2)`) is necessary to obtain
`file_length`.  When reading the footer, readers must verify:

- 4-byte magic is correct
- 1-byte version number is recognized
- 4-byte CRC-32 matches the other 64 bytes (including magic, and version)

Once verified, the other fields of the footer can be accessed.

### Varint encoding

Varint encoding is identical to the ofs-delta encoding method used
within pack files.

Decoder works such as:

    val = buf[ptr] & 0x7f
    while (buf[ptr] & 0x80) {
      ptr++
      val = ((val + 1) << 7) | (buf[ptr] & 0x7f)
    }

### Binary search

Binary search within a block is supported by the `restart_offset`
fields at the end of the block.  Readers can binary search through the
restart table to locate between which two restart points the sought
reference or key should appear.

Each record identified by a `restart_offset` stores the complete key
in the `suffix` field of the record, making the compare operation
during binary search straightforward.

Once a restart point lexicographically before the sought reference has
been identified, readers can linearly scan through the following
record entries to locate the sought record, terminating if the current
record sorts after (and therefore the sought key is not present).

#### Restart point selection

Writers determine the restart points at file creation.  The process is
arbitrary, but every 16 or 64 records is recommended.  Every 16 may
be more suitable for smaller block sizes (4k or 8k), every 64 for
larger block sizes (64k).

More frequent restart points reduces prefix compression and increases
space consumed by the restart table, both of which increase file size.

Less frequent restart points makes prefix compression more effective,
decreasing overall file size, with increased penalities for readers
walking through more records after the binary search step.

A maximum of `65535` restart points per block is supported.

## Considerations

### Lightweight refs dominate

The reftable format assumes the vast majority of references are single
SHA-1 valued with common prefixes, such as Gerrit Code Review's
`refs/changes/` namespace, GitHub's `refs/pulls/` namespace, or many
lightweight tags in the `refs/tags/` namespace.

Annotated tags storing the peeled object cost only an additional 20
bytes per reference.

### Low overhead

A reftable with very few references (e.g. git.git with 5 heads)
is 274 bytes for reftable, vs. 332 bytes for packed-refs.  This
supports reftable scaling down for transaction logs (below).

### Block size

For a Gerrit Code Review type repository with many change refs, larger
block sizes (64 KiB) and less frequent restart points (every 64) yield
better compression due to more references within the block compressing
against the prior reference.

Larger block sizes reduces the index size, as the reftable will
require fewer blocks to store the same number of references.

### Minimal disk seeks

Assuming the index block has been loaded into memory, binary searching
for any single reference requires exactly 1 disk seek to load the
containing block.

### Scans and lookups dominate

Scanning all references and lookup by name (or namespace such as
`refs/heads/`) are the most common activities performed by repositories.
SHA-1s are stored twice when obj blocks are present, avoiding disk
seeks for the common cases of scan and lookup by name.

### Logs are infrequently read

Logs are infrequently accessed, but can be large.  Deflating log
blocks saves disk space, with some increased penalty at read time.

Logs are stored in an isolated section from refs, reducing the burden
on reference readers that want to ignore logs.  Further, historical
logs can be isolated into log-only files.

### Logs are read backwards

Logs are frequently accessed backwards (most recent N records for
master to answer `master@{4}`), so log records are grouped by
reference, and sorted descending by update index.

## Repository format

### Version 1

A repository must set its `$GIT_DIR/config` to configure reftable:

    [core]
        repositoryformatversion = 1
    [extensions]
        refStorage = reftable

### Layout

The `$GIT_DIR/refs` path is a file when reftable is configured, not a
directory.  This prevents loose references from being stored.

A collection of reftable files are stored in the `$GIT_DIR/reftable/`
directory:

    00000001_UF4paF
    00000002_bUVgy4

where reftable files are named by a unique name such as produced by
the function:

    mktemp "${update_index}_XXXXXX"

The stack ordering file is `$GIT_DIR/refs` and lists the current
files, one per line, in order, from oldest (base) to newest (most
recent):

    $ cat .git/refs
    00000001_UF4paF
    00000002_bUVgy4

Readers must read `$GIT_DIR/refs` to determine which files are
relevant right now, and search through the stack in reverse order
(last reftable is examined first).

Reftable files not listed in `refs` may be new (and about to be added
to the stack by the active writer), or ancient and ready to be pruned.

### Update transactions

Although reftables are immutable, mutations are supported by writing a
new reftable and atomically appending it to the stack:

1. Acquire `refs.lock`.
2. Read `refs` to determine current reftables.
3. Select `update_index` to be most recent file's `max_update_index + 1`.
4. Prepare new reftable `${update_index}_XXXXXX`, including log entries.
5. Copy `refs` to `refs.lock`, appending file from (4).
6. Rename `refs.lock` to `refs`.

During step 4 the new file's `min_update_index` and `max_update_index`
are both set to the `update_index` selected by step 3.  All log
records for the transaction use the same `update_index` in their keys.
This enables later correlation of which references were updated by the
same transaction.

Because a single `refs.lock` file is used to manage locking, the
repository is single-threaded for writers.  Writers may have to
busy-spin (with backoff) around creating `refs.lock`, for up to an
acceptable wait period, aborting if the repository is too busy to
mutate.  Application servers wrapped around repositories (e.g.  Gerrit
Code Review) can layer their own lock/wait queue to improve fairness
to writers.

### Reference deletions

Deletion of any reference can be explicitly stored by setting the
`type` to `0x0` and omitting the `value` field of the `ref_record`.
This entry shadows the reference in earlier files in the stack.

### Compaction

A partial stack of reftables can be compacted by merging references
using a straightforward merge join across reftables, selecting the
most recent value for output, and omitting deleted references that do
not appear in remaining, lower reftables.

A compacted reftable should set its `min_update_index` to the smallest of
the input files' `min_update_index`, and its `max_update_index`
likewise to the largest input `max_update_index`.

For sake of illustration, assume the stack currently consists of
reftable files (from oldest to newest): A, B, C, and D. The compactor
is going to compact B and C, leaving A and D alone.

1.  Obtain lock `refs.lock` and read the `refs` file.
2.  Obtain locks `B.lock` and `C.lock`.
    Ownership of these locks prevents other processes from trying
    to compact these files.
3.  Release `refs.lock`.
4.  Compact `B` and `C` into a new file `${min_update_index}_XXXXXX`.
5.  Reacquire lock `refs.lock`.
6.  Verify that `B` and `C` are still in the stack, in that order. This
    should always be the case, assuming that other processes are adhering
    to the locking protocol.
7.  Write the new stack to `refs.lock`, replacing `B` and `C` with the
    file from (4).
8.  Rename `refs.lock` to `refs`.
9.  Delete `B` and `C`, perhaps after a short sleep to avoid forcing
    readers to backtrack.

This strategy permits compactions to proceed independently of updates.

## Alternatives considered

### bzip packed-refs

`bzip2` can significantly shrink a large packed-refs file (e.g. 62
MiB compresses to 23 MiB, 37%).  However the bzip format does not support
random access to a single reference. Readers must inflate and discard
while performing a linear scan.

Breaking packed-refs into chunks (individually compressing each chunk)
would reduce the amount of data a reader must inflate, but still
leaves the problem of indexing chunks to support readers efficiently
locating the correct chunk.

Given the compression achieved by reftable's encoding, it does not
seem necessary to add the complexity of bzip/gzip/zlib.

### Michael Haggerty's alternate format

Michael Haggerty proposed [an alternate][mh-alt] format to reftable on
the Git mailing list.  This format uses smaller chunks, without the
restart table, and avoids block aligning with padding.  Reflog entries
immediately follow each ref, and are thus interleaved between refs.

Performance testing indicates reftable is faster for lookups (51%
faster, 11.2 usec vs.  5.4 usec), although reftable produces a
slightly larger file (+ ~3.2%, 28.3M vs 29.2M):

format    |  size  | seek cold | seek hot  |
---------:|-------:|----------:|----------:|
mh-alt    | 28.3 M | 23.4 usec | 11.2 usec |
reftable  | 29.2 M | 19.9 usec |  5.4 usec |

[mh-alt]: https://public-inbox.org/git/CAMy9T_HCnyc1g8XWOOWhe7nN0aEFyyBskV2aOMb_fe+wGvEJ7A@mail.gmail.com/

### JGit Ketch RefTree

[JGit Ketch][ketch] proposed [RefTree][reftree], an encoding of
references inside Git tree objects stored as part of the repository's
object database.

The RefTree format adds additional load on the object database storage
layer (more loose objects, more objects in packs), and relies heavily
on the packer's delta compression to save space.  Namespaces which are
flat (e.g.  thousands of tags in refs/tags) initially create very
large loose objects, and so RefTree does not address the problem of
copying many references to modify a handful.

Flat namespaces are not efficiently searchable in RefTree, as tree
objects in canonical formatting cannot be binary searched. This fails
the need to handle a large number of references in a single namespace,
such as GitHub's `refs/pulls`, or a project with many tags.

[ketch]: https://dev.eclipse.org/mhonarc/lists/jgit-dev/msg03073.html
[reftree]: https://public-inbox.org/git/CAJo=hJvnAPNAdDcAAwAvU9C4RVeQdoS3Ev9WTguHx4fD0V_nOg@mail.gmail.com/

### LMDB

David Turner proposed [using LMDB][dt-lmdb], as LMDB is lightweight
(64k of runtime code) and GPL-compatible license.

A downside of LMDB is its reliance on a single C implementation.  This
makes embedding inside JGit (a popular reimplemenation of Git)
difficult, and hoisting onto virtual storage (for JGit DFS) virtually
impossible.

A common format that can be supported by all major Git implementations
(git-core, JGit, libgit2) is strongly preferred.

[dt-lmdb]: https://public-inbox.org/git/1455772670-21142-26-git-send-email-dturner@twopensource.com/

## Future

### Longer hashes

Version will bump (e.g.  2) to indicate `value` uses a different
object id length other than 20.  The length could be stored in an
expanded file header, or hardcoded as part of the version.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-07  1:47 reftable [v6]: new ref storage format Shawn Pearce
@ 2017-08-07 18:27 ` Stefan Beller
  2017-08-07 18:30   ` Shawn Pearce
  2017-08-08  7:28 ` Jeff King
                   ` (3 subsequent siblings)
  4 siblings, 1 reply; 14+ messages in thread
From: Stefan Beller @ 2017-08-07 18:27 UTC (permalink / raw)
  To: Shawn Pearce
  Cc: git, Jeff King, Michael Haggerty, Junio C Hamano, David Borowitz

On Sun, Aug 6, 2017 at 6:47 PM, Shawn Pearce <spearce@spearce.org> wrote:
> 6th iteration of the reftable storage format.
>
> You can read a rendered version of this here:
> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md
>
> Changes from v5:
> - extensions.refStorage = reftable is used to select this format.
>
> - Log records can be explicitly deleted (for refs/stash).
> - Log records may use Michael Haggerty's chained idea to compress before zlib.
>   This saved ~5.8% on one of my example repositories.

Some observations:

Also the bits in the records changed in v5 or v6:
  0x0..0x3 is valid for a ref,
  obj records have a ccnt
  0x0, 0x1, 0x4..0x7 are used in the logs

We have the following block indicators:
  'r'  ref block
  'o' object block
  'g' log block

  high bit for any index.

Without prior knowledge an index doesn't indicate if it
indexes refs, objects or logs. To find out, one must follow
an arbitrary entry which points to either an index again
or at a block marked with 'r', 'o' or 'g'.

Okay with me.

> The index may be organized into a multi-level index, where ...
> which may in turn point to either index blocks (3rd level) or ref blocks (leaf level).

So we allow 3 levels at most?

The file format structure marks the indexes '?', should that be
rather '*' to indicate there can be more than one index block?

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-07 18:27 ` Stefan Beller
@ 2017-08-07 18:30   ` Shawn Pearce
  2017-08-08 23:52     ` Stefan Beller
  0 siblings, 1 reply; 14+ messages in thread
From: Shawn Pearce @ 2017-08-07 18:30 UTC (permalink / raw)
  To: Stefan Beller
  Cc: git, Jeff King, Michael Haggerty, Junio C Hamano, David Borowitz

On Mon, Aug 7, 2017 at 11:27 AM, Stefan Beller <sbeller@google.com> wrote:
> On Sun, Aug 6, 2017 at 6:47 PM, Shawn Pearce <spearce@spearce.org> wrote:
>> 6th iteration of the reftable storage format.
>>
>> You can read a rendered version of this here:
>> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md
>>
>> The index may be organized into a multi-level index, where ...
>> which may in turn point to either index blocks (3rd level) or ref blocks (leaf level).
>
> So we allow 3 levels at most?

No, its just an example. Large ref sets with small block size need 4
levels. Or more.

> The file format structure marks the indexes '?', should that be
> rather '*' to indicate there can be more than one index block?

Will fix in the next respin of the document, thanks.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-07  1:47 reftable [v6]: new ref storage format Shawn Pearce
  2017-08-07 18:27 ` Stefan Beller
@ 2017-08-08  7:28 ` Jeff King
  2017-08-08 19:01 ` Junio C Hamano
                   ` (2 subsequent siblings)
  4 siblings, 0 replies; 14+ messages in thread
From: Jeff King @ 2017-08-08  7:28 UTC (permalink / raw)
  To: Shawn Pearce
  Cc: git, Michael Haggerty, Junio C Hamano, David Borowitz,
	Stefan Beller

On Sun, Aug 06, 2017 at 06:47:06PM -0700, Shawn Pearce wrote:

> Changes from v5:
> - extensions.refStorage = reftable is used to select this format.

Thanks, I think this is a better scheme going forward. Just a few notes
on compatibility while I'm thinking about it:

  - existing versions will complain that they don't know what the
    "refStorage" extension is

  - presumably we'd add new code that recognizes the extension, and then
    makes sure the value is something we understand.

  - then we'd finally mark "reftable" as understood once we had an
    implementation. We _could_ then also check other config (like
    "reftable.*") and complain about unknown keys. But I think we could
    declare any such keys as optional, and just rely on the version
    number inside the reftable file for parsing it.

-Peff

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-07  1:47 reftable [v6]: new ref storage format Shawn Pearce
  2017-08-07 18:27 ` Stefan Beller
  2017-08-08  7:28 ` Jeff King
@ 2017-08-08 19:01 ` Junio C Hamano
  2017-08-08 22:27   ` Shawn Pearce
  2017-08-08 19:25 ` Junio C Hamano
  2017-08-14 12:13 ` Michael Haggerty
  4 siblings, 1 reply; 14+ messages in thread
From: Junio C Hamano @ 2017-08-08 19:01 UTC (permalink / raw)
  To: Shawn Pearce
  Cc: git, Jeff King, Michael Haggerty, David Borowitz, Stefan Beller

I notice that you raised the location of restart table within a
block in this iteration (or maybe it happened in v5).  

This forces you to hold all contents in core before the first byte
is written out.  You start from the first entry (which will become
the first restart entry), emit a handful as prefix compressed
entries, emit a full entry (which will become the next restart
entry), ... until you have enough to fill both the data and the
restart table, then start writing from the header (which needs the
length of the block), restart table and then data.

I think it is OK to do so for the blocks whose size is limited to
16M, but I wonder if it is sensible to do the same for the index
block whose limit is 2G.  If you keep the restart table after the
data, then you could stream out the entries as you emit, write the
restart table, and then seek back to fix the length in the header,
without holding the 2G in core, no?


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-07  1:47 reftable [v6]: new ref storage format Shawn Pearce
                   ` (2 preceding siblings ...)
  2017-08-08 19:01 ` Junio C Hamano
@ 2017-08-08 19:25 ` Junio C Hamano
  2017-08-08 22:30   ` Shawn Pearce
  2017-08-14 12:13 ` Michael Haggerty
  4 siblings, 1 reply; 14+ messages in thread
From: Junio C Hamano @ 2017-08-08 19:25 UTC (permalink / raw)
  To: Shawn Pearce
  Cc: git, Jeff King, Michael Haggerty, David Borowitz, Stefan Beller

Shawn Pearce <spearce@spearce.org> writes:

> For `log_type = 0x4..0x7` the `log_chained` section is used instead to
> compress information that already appeared in a prior log record.  The
> `log_chained` always includes `old_id` for this record, as `new_id` is
> implied by the prior (by file order, more recent) record's `old_id`.
>
> The `not_same_committer` block appears if `log_type & 0x1` is true,
> `not_same_message` block appears if `log_type & 0x2` is true.  When
> one of these blocks is missing, its values are implied by the prior
> (more recent) log record.

Two comments.

 * not-same-committer would be what I would use when I switch
   timezones, even if I stay to be me, right?  I am just wondering
   if it is clear to everybody that "committer" in that phrase is a
   short-hand for "committer information other than the timestamp".

 * Should the set of entries that are allowed to use of "chained"
   log be related to the set of entries that appear in the restart
   table in any way?  For a reader that scans starting at a restart
   point, it would be very cumbersome if the entry were chained from
   the previous entry, as it would force it to backtrack entries to
   find the first non-chained log entry.  A simple "log_chained must
   not be used for an entry that appear in the restart table" rule
   would solve that, but I didn't see it in the document.




^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-08 19:01 ` Junio C Hamano
@ 2017-08-08 22:27   ` Shawn Pearce
  2017-08-08 23:34     ` Junio C Hamano
  0 siblings, 1 reply; 14+ messages in thread
From: Shawn Pearce @ 2017-08-08 22:27 UTC (permalink / raw)
  To: Junio C Hamano
  Cc: git, Jeff King, Michael Haggerty, David Borowitz, Stefan Beller

On Tue, Aug 8, 2017 at 12:01 PM, Junio C Hamano <gitster@pobox.com> wrote:
> I notice that you raised the location of restart table within a
> block in this iteration (or maybe it happened in v5).
>
> This forces you to hold all contents in core before the first byte
> is written out.  You start from the first entry (which will become
> the first restart entry), emit a handful as prefix compressed
> entries, emit a full entry (which will become the next restart
> entry), ... until you have enough to fill both the data and the
> restart table, then start writing from the header (which needs the
> length of the block), restart table and then data.
>
> I think it is OK to do so for the blocks whose size is limited to
> 16M, but I wonder if it is sensible to do the same for the index
> block whose limit is 2G.  If you keep the restart table after the
> data, then you could stream out the entries as you emit, write the
> restart table, and then seek back to fix the length in the header,
> without holding the 2G in core, no?

Yes. I'm torn on the ordering: restart table first or restart table last.

The advantage of it first is the reader can immediately work with it,
without necessarily touching the rest of the block. The disadvantage
is a writer can only stream at block sizes, as the writer is forced to
buffer the entire block. As it happens my implementation in JGit
buffers the entire block anyway, so this didn't really factor as an
issue for me.

Given that the index can now also be multi-level, I don't expect to
see a 2G index. A 2G index forces the reader to load the entire 2G to
take advantage of the restart table. It may be more efficient for such
a reader to have had the writer make a mutli-level index, instead of a
single monster index block. And so perhaps the writer shouldn't make a
2G index block that she is forced to buffer. :)

Perhaps I'll move it back to the tail of the block. I can see the
streaming writer code is maybe more straightforward that way.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-08 19:25 ` Junio C Hamano
@ 2017-08-08 22:30   ` Shawn Pearce
  0 siblings, 0 replies; 14+ messages in thread
From: Shawn Pearce @ 2017-08-08 22:30 UTC (permalink / raw)
  To: Junio C Hamano
  Cc: git, Jeff King, Michael Haggerty, David Borowitz, Stefan Beller

On Tue, Aug 8, 2017 at 12:25 PM, Junio C Hamano <gitster@pobox.com> wrote:
> Shawn Pearce <spearce@spearce.org> writes:
>
>> For `log_type = 0x4..0x7` the `log_chained` section is used instead to
>> compress information that already appeared in a prior log record.  The
>> `log_chained` always includes `old_id` for this record, as `new_id` is
>> implied by the prior (by file order, more recent) record's `old_id`.
>>
>> The `not_same_committer` block appears if `log_type & 0x1` is true,
>> `not_same_message` block appears if `log_type & 0x2` is true.  When
>> one of these blocks is missing, its values are implied by the prior
>> (more recent) log record.
>
> Two comments.
>
>  * not-same-committer would be what I would use when I switch
>    timezones, even if I stay to be me, right?

Correct. This is based on the theory that the timezone in a reflog is
actually the system timezone, not your timezone. If you push to a
remote system, that system's reflog will be using that system's
timezone, not your timezone. So you aren't really that different, and
we can compress the timezone part away. Also, if you do move
timezones, you are likely to remain in that timezone for some period
of time, and such we can compress many log records again with the same
timezone+name+email.

Its ancient history from my research with "pack v4", but people don't
really change timezones very often in the Git committer data. I
suspect its even more true with reflog data.

>  I am just wondering
>    if it is clear to everybody that "committer" in that phrase is a
>    short-hand for "committer information other than the timestamp".

Maybe not. I will try to come up with another shorthand name for this.

>  * Should the set of entries that are allowed to use of "chained"
>    log be related to the set of entries that appear in the restart
>    table in any way?  For a reader that scans starting at a restart
>    point, it would be very cumbersome if the entry were chained from
>    the previous entry, as it would force it to backtrack entries to
>    find the first non-chained log entry.  A simple "log_chained must
>    not be used for an entry that appear in the restart table" rule
>    would solve that, but I didn't see it in the document.

Good catch!  This is implemented as you described in JGit (for the
reasons you described), but not documented. I'll fix it.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-08 22:27   ` Shawn Pearce
@ 2017-08-08 23:34     ` Junio C Hamano
  2017-08-09  0:01       ` Shawn Pearce
  0 siblings, 1 reply; 14+ messages in thread
From: Junio C Hamano @ 2017-08-08 23:34 UTC (permalink / raw)
  To: Shawn Pearce
  Cc: git, Jeff King, Michael Haggerty, David Borowitz, Stefan Beller

Shawn Pearce <spearce@spearce.org> writes:

> Given that the index can now also be multi-level, I don't expect to
> see a 2G index. A 2G index forces the reader to load the entire 2G to
> take advantage of the restart table. It may be more efficient for such
> a reader to have had the writer make a mutli-level index, instead of a
> single monster index block. And so perhaps the writer shouldn't make a
> 2G index block that she is forced to buffer. :)

Ah, OK, then it is sensible to have all table blocks to have the
same format, and restart at the beginning to help readers would be a
fine choice.  For the same "let's make them as consistent" sake, I
am tempted to suggest that we lift "the index block can be 2G" and
have it also be within uint_24(), perhaps?  Otherwise the readers
would have to read (or mmap) the whole 2G.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-07 18:30   ` Shawn Pearce
@ 2017-08-08 23:52     ` Stefan Beller
  0 siblings, 0 replies; 14+ messages in thread
From: Stefan Beller @ 2017-08-08 23:52 UTC (permalink / raw)
  To: Shawn Pearce
  Cc: git, Jeff King, Michael Haggerty, Junio C Hamano, David Borowitz

On Mon, Aug 7, 2017 at 11:30 AM, Shawn Pearce <spearce@spearce.org> wrote:
> On Mon, Aug 7, 2017 at 11:27 AM, Stefan Beller <sbeller@google.com> wrote:
>> On Sun, Aug 6, 2017 at 6:47 PM, Shawn Pearce <spearce@spearce.org> wrote:
>>> 6th iteration of the reftable storage format.
>>>
>>> You can read a rendered version of this here:
>>> https://googlers.googlesource.com/sop/jgit/+/reftable/Documentation/technical/reftable.md
>>>
>>> The index may be organized into a multi-level index, where ...
>>> which may in turn point to either index blocks (3rd level) or ref blocks (leaf level).
>>
>> So we allow 3 levels at most?
>
> No, its just an example. Large ref sets with small block size need 4
> levels. Or more.

A malicious (or buggy) writer can produce indexes pointing to
each other producing a circle. (Who would do that?)

A reader should  - instead of segfaulting due to unbounded
recursion or being stuck in an infinite loop - ignore the indexes
in this case and fallback to the slow non-indexed behavior,
i.e. while the file format allows for unbounded levels, a reader
should not.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-08 23:34     ` Junio C Hamano
@ 2017-08-09  0:01       ` Shawn Pearce
  0 siblings, 0 replies; 14+ messages in thread
From: Shawn Pearce @ 2017-08-09  0:01 UTC (permalink / raw)
  To: Junio C Hamano
  Cc: git, Jeff King, Michael Haggerty, David Borowitz, Stefan Beller

On Tue, Aug 8, 2017 at 4:34 PM, Junio C Hamano <gitster@pobox.com> wrote:
> Shawn Pearce <spearce@spearce.org> writes:
>
>> Given that the index can now also be multi-level, I don't expect to
>> see a 2G index. A 2G index forces the reader to load the entire 2G to
>> take advantage of the restart table. It may be more efficient for such
>> a reader to have had the writer make a mutli-level index, instead of a
>> single monster index block. And so perhaps the writer shouldn't make a
>> 2G index block that she is forced to buffer. :)
>
> Ah, OK, then it is sensible to have all table blocks to have the
> same format, and restart at the beginning to help readers would be a
> fine choice.  For the same "let's make them as consistent" sake, I
> am tempted to suggest that we lift "the index block can be 2G" and
> have it also be within uint_24(), perhaps?  Otherwise the readers
> would have to read (or mmap) the whole 2G.

Gah. I just finished moving the restart table back to the end of the block. :)

However, I think I can agree with the index fitting into the uint24
size of 15M, and asking writers making an index that exceeds that to
use multi-level indexing.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-07  1:47 reftable [v6]: new ref storage format Shawn Pearce
                   ` (3 preceding siblings ...)
  2017-08-08 19:25 ` Junio C Hamano
@ 2017-08-14 12:13 ` Michael Haggerty
  4 siblings, 0 replies; 14+ messages in thread
From: Michael Haggerty @ 2017-08-14 12:13 UTC (permalink / raw)
  To: Shawn Pearce, git, Jeff King
  Cc: Junio C Hamano, David Borowitz, Stefan Beller

On 08/07/2017 03:47 AM, Shawn Pearce wrote:
> 6th iteration of the reftable storage format.

Thanks!

> Changes from v5:
> - extensions.refStorage = reftable is used to select this format.
> 
> - Log records can be explicitly deleted (for refs/stash).
> - Log records may use Michael Haggerty's chained idea to compress before zlib.
>   This saved ~5.8% on one of my example repositories.

Meh. Do you think that's worth the complexity? The percentage savings
will presumably be even lower for repositories that store significant
information in their reflog messages.

> [...]
> #### ref record
> 
> A `ref_record` describes a single reference, storing both the name and
> its value(s). Records are formatted as:
> 
>     varint( prefix_length )
>     varint( (suffix_length << 3) | value_type )
>     suffix
>     value?
> 
> [...]
> - `0x0`: deletion; no value data (see transactions, below)
> - `0x1`: one 20-byte object id; value of the ref
> - `0x2`: two 20-byte object ids; value of the ref, peeled target
> - `0x3`: symref and text: `varint( text_len ) text`
> 
> Symbolic references use `0x3` with a `text` string starting with `"ref: "`,
> followed by the complete name of the reference target.  No
> compression is applied to the target name.  Other types of contents
> that are also reference like, such as `FETCH_HEAD` and `MERGE_HEAD`,
> may also be stored using type `0x3`.

I'm still relatively negative on storing "other" references (except
`HEAD`) in reftable. Here are my thoughts:

* "Other" references are not considered for reachability, so there
  is no need for their modification to be done atomically.

* "Other" references don't have or need reflogs.

* The refs API would have to provide a way for other Git code to
  read and write "other" references including their extra
  information, and the users of that information would have to
  be rewritten to use the new API.

* Presumably there are other programs in the wild (e.g., scripts)
  that want to read that information. They wouldn't be able to
  extract it from reftable files themselves, so we would also have
  to provide a command-line tool to read (and write?) such files.

> Types `0x4..0x7` are reserved for future use.

Regardless, I suggest allocating separate `value_type`s for generic
symrefs (which then wouldn't need a `ref: ` prefix) vs. for "other"
references.

> [...]
> ### Ref index

It wasn't clear to me whether (in the case of a multi-level index) ref
index blocks have to be aligned in `block_size` blocks (both their
maximum size and their alignment). I don't see a reason for that to be
required, though of course a compactor implementation might choose to
block-align these blocks based on the filesystem that is in use.

For that matter, I don't see an intrinsic reason that object blocks or
object index blocks need to be block aligned.

In fact, the only way I can see that the current reftable proposal makes
use of `block_size` is so that `obj_record`s can record `block_delta` in
units of `block_size` rather than in units of bytes. (And given that I'm
skeptical about the value of the object index, that justification seems
thin.)

I totally accept that *you* want to align your blocks, and I'm totally
supportive of a format that permits a reftable compactor to write
reftables that are block-aligned. It just still seems to me that it
imposes more complexity than necessary on *other* reftable compactor
implementations that don't care about block alignment.

Aside from the object index, I think it would be straightforward to
write a reftable reader that is totally ignorant of `block_size`.

So unless I've overlooked something, I think the following plan wouldn't
cause you any extra trouble, but would make it easier to implement a
compactor that doesn't care about block sizes or object indexes:

If a reftable has an object index, then `block_size` must be specified,
and ref blocks *must* be aligned to start at multiples of `block_size`.

However, if a reftable has no object index, then its `block_size` is
only a hint about the typical block size; e.g., "if you want to read a
full block, then try reading `block_size` and you'll probably get the
whole thing". And if `block_size` is zero, then readers get no guidance
about the typical block size (which would be just fine for an mmap-based
reader).

Essentially, choices about block alignment would become a
quality-of-implementation issue for reftable compactors, and readers
would hardly need to care.

> [...]
> #### index record
> 
> An index record describes the last entry in another block.
> Index records are written as:
> 
>     varint( prefix_length )
>     varint( (suffix_length << 3) | 0 )
>     suffix
>     varint( block_position )
> 
> Index records use prefix compression exactly like `ref_record`.
> 
> Index records store `block_position` after the suffix, specifying the
> absolute position in bytes (from the start of the file) of the block
> that ends with this reference.

Is there a reason that the index lists the *last* refname that is
contained in a block rather than the *first* refname? I can't think of a
reason to choose one vs. the other, but your choice was initially
surprising. I don't think it matters either way; I was just curious.

Do I understand correctly that all `block_position`s are *byte*
addresses, even in the `ref_index` where they should all be multiples of
the block size (except the zeroth one)? I think that's OK, but note that
it will waste more than a byte per `ref_index` and `obj_index` record,
on average.

> Readers must examine the block header at `block_position` to determine
> if the next block is another level index block, or the leaf-level ref
> block.

For scanning through a whole namespace, like `refs/tags/`, I guess you
only need to use a binary search to find the beginning of the range.
Then you would read serially forwards from there, continuing from one
`ref_block` to the next, until you find a refname that doesn't start
with `refs/tags/`. In other words, there is no reason to binary search
to find the end of the namespace, correct? [1]

The same approach would be used to scan the reflog of a reference.

[1] I suppose binary searching to find the end of the namespace might be
useful for a high-latency filesystem, as you could initiate a pre-fetch
for all of the storage blocks that are expected to be needed rather than
initiating the read of the next block only after having processed the
previous block.

> [...]
> #### log record
> [...]
>     log_chained {
>       old_id
>       varint( time_seconds )
>       not_same_committer {
>         sint16( tz_offset )
>         varint( name_length    )  name
>         varint( email_length   )  email
>       }?
>       not_same_message {
>         varint( message_length )  message
>       }?
>     }
> ```
> 
> Log record entries use `log_type` to indicate what follows:
> 
> - `0x0`: deletion; no log data.
> - `0x1`: standard git reflog data using `log_data` above.
> - `0x2..0x3`: reserved for future use.
> - `0x4..0x7`: `log_chained`, with conditional members.
> 
> [...]
> For `log_type = 0x4..0x7` the `log_chained` section is used instead to
> compress information that already appeared in a prior log record.  The
> `log_chained` always includes `old_id` for this record, as `new_id` is
> implied by the prior (by file order, more recent) record's `old_id`.
> 
> The `not_same_committer` block appears if `log_type & 0x1` is true,
> `not_same_message` block appears if `log_type & 0x2` is true.  When
> one of these blocks is missing, its values are implied by the prior
> (more recent) log record.

Just to make sure that we are on the same page...

`old_id` and `new_id` in adjacent reflog entries are not always
identical. If you run `git reflog expire` or `git reflog delete` without
the `--rewrite` option, then the to-be-deleted entries are just dropped
without changing the neighboring entries to chain together again.

This would have to be supported in your proposal by writing a full
`log_data` record for the entry following such a gap.

> [...]
> #### Importing logs
> 
> When importing from `$GIT_DIR/logs` writers should globally order all
> log records roughly by timestamp while preserving file order, and
> assign unique, increasing `update_index` values for each log line.
> Newer log records get higher `update_index` values.
> 
> Although an import may write only a single reftable file, the reftable
> file must span many unique `update_index`, as each log line requires
> its own `update_index` to preserve semantics.

Thinking out loud here: A really high-quality importer might want to
group together, under the same `update_index`, ref updates that are
thought originally to have been done in the same transaction.

* Only group entries with the same timestamps and log messages
  should be grouped together.

* There should not be more than one update to a particular
  reference in a single transaction.

* Ideally, it would avoid creating states between `update-index`es
  where references D/F-conflict with each other. (Given that reflogs
  can be expired, this is not always possible in the general case.)

* It could theoretically even reconstruct "branch rename" operations
  that required temporary reference names into a single `update_index`.

But I doubt that it is worth the effort. (The whole idea gives me nasty
flashbacks from working on cvs2svn/cvs2git.)

> [...]
> ### Layout
> 
> The `$GIT_DIR/refs` path is a file when reftable is configured, not a
> directory.  This prevents loose references from being stored.
> 
> A collection of reftable files are stored in the `$GIT_DIR/reftable/`
> directory:
> 
>     00000001_UF4paF
>     00000002_bUVgy4
> 
> where reftable files are named by a unique name such as produced by
> the function:
> 
>     mktemp "${update_index}_XXXXXX"

Please note that if reflogs are compacted into a separate "reflog-only"
file, then the same `update_index` might appear in the filename of both
a "reflog-only" file and a value-only file. I don't think that this is a
problem, but we shouldn't bake assumptions about uniqueness into the system.

I'm a little bit worried that users might automatically think that a
filename that includes a string like `UF4paF` is a temporary file and
"clean it up" (with disastrous consequences). It might be prudent to
give the files names that don't look so garbagy.

And wouldn't it be nice to tack a filename extension onto the end of
these filenames to make them more easily recognizable?

> The stack ordering file is `$GIT_DIR/refs` and lists the current
> files, one per line, in order, from oldest (base) to newest (most
> recent):
> 
>     $ cat .git/refs
>     00000001_UF4paF
>     00000002_bUVgy4
> 
> Readers must read `$GIT_DIR/refs` to determine which files are
> relevant right now, and search through the stack in reverse order
> (last reftable is examined first).
> 
> Reftable files not listed in `refs` may be new (and about to be added
> to the stack by the active writer), or ancient and ready to be pruned.

It might be good to think about how readers should work. The easy
implementation would be:

1. Open and read the `refs` file
2. Open each of the reftable files that it mentions
3. If any of the files is missing, goto 1 (with some checks to avoid
   infinite loops).
4. Read from the now-open files as long as you need to.

This would give you a self-consistent snapshot of the global reference
state. However, a long-running program (especially one dealing with
reachability) might want to check at strategic moments that the `refs`
file hasn't changed out from under it while it was running, or even lock
the `refs` file during critical operations.

It would be possible to avoid opening all of the reftable files right
away in the hope that the reference that you seek is in one of the top
few files. But this quickly gets tricky because you might read some
references from the top reftable, then need to dig deeper for another
reference only to find out that one of the deeper files is no longer in
the stack. So in one program run you might end up seeing reference
values from two different snapshots.

> [...]

Michael

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
@ 2017-08-15 22:47 Shawn Pearce
  2017-08-18  9:24 ` Michael Haggerty
  0 siblings, 1 reply; 14+ messages in thread
From: Shawn Pearce @ 2017-08-15 22:47 UTC (permalink / raw)
  To: Michael Haggerty
  Cc: git, Jeff King, Junio C Hamano, David Borowitz, Stefan Beller

On Mon, Aug 14, 2017 at 5:13 AM, Michael Haggerty <mhagger@alum.mit.edu> wrote:
> On 08/07/2017 03:47 AM, Shawn Pearce wrote:
>> 6th iteration of the reftable storage format.
>
> Thanks!
>
>> Changes from v5:
>> - extensions.refStorage = reftable is used to select this format.
>>
>> - Log records can be explicitly deleted (for refs/stash).
>> - Log records may use Michael Haggerty's chained idea to compress before zlib.
>>   This saved ~5.8% on one of my example repositories.
>
> Meh. Do you think that's worth the complexity? The percentage savings
> will presumably be even lower for repositories that store significant
> information in their reflog messages.

No, I don't. I'm quite happy to remove the chained compression. I'll
keep the explicit deletion support for refs/stash.


>> [...]
>> #### ref record
>> - `0x3`: symref and text: `varint( text_len ) text`
[...]
> I'm still relatively negative on storing "other" references (except
> `HEAD`) in reftable. Here are my thoughts:
>
> * "Other" references are not considered for reachability, so there
>   is no need for their modification to be done atomically.
>
> * "Other" references don't have or need reflogs.
>
> * The refs API would have to provide a way for other Git code to
>   read and write "other" references including their extra
>   information, and the users of that information would have to
>   be rewritten to use the new API.
>
> * Presumably there are other programs in the wild (e.g., scripts)
>   that want to read that information. They wouldn't be able to
>   extract it from reftable files themselves, so we would also have
>   to provide a command-line tool to read (and write?) such files.
>
> Regardless, I suggest allocating separate `value_type`s for generic
> symrefs (which then wouldn't need a `ref: ` prefix) vs. for "other"
> references.

Ack, I agree with you. Lets only store symrefs as 0x3, without the
"ref: " prefix nonsense, and don't support the "other" ref types. You
make good arguments above about why those would not be stored in a
reftable.


>> [...]
>> ### Ref index
>
> It wasn't clear to me whether (in the case of a multi-level index) ref
> index blocks have to be aligned in `block_size` blocks (both their
> maximum size and their alignment). I don't see a reason for that to be
> required, though of course a compactor implementation might choose to
> block-align these blocks based on the filesystem that is in use.
>
> For that matter, I don't see an intrinsic reason that object blocks or
> object index blocks need to be block aligned.

Yea, you are correct. There isn't an actual need for alignment.

> In fact, the only way I can see that the current reftable proposal makes
> use of `block_size` is so that `obj_record`s can record `block_delta` in
> units of `block_size` rather than in units of bytes. (And given that I'm
> skeptical about the value of the object index, that justification seems
> thin.)

This use of block_size in the obj_record also has been bothering me.
I'm changing it to use position, which removes any requirement on
alignment. It does cost a bit more space, but I'm willing to trade
that for simplification in the format definition.

> I totally accept that *you* want to align your blocks, and I'm totally
> supportive of a format that permits a reftable compactor to write
> reftables that are block-aligned. It just still seems to me that it
> imposes more complexity than necessary on *other* reftable compactor
> implementations that don't care about block alignment.
>
> Aside from the object index, I think it would be straightforward to
> write a reftable reader that is totally ignorant of `block_size`.

Yup, I think you are right. So I'll try to rework the document to make
it so alignment and padding are writer-local decisions. A writer can
choose to align, or choose to skip alignment. Readers should be
prepared for either.


>> [...]
>> #### index record
>>
>> An index record describes the last entry in another block.
>> Index records are written as:
>>
>>     varint( prefix_length )
>>     varint( (suffix_length << 3) | 0 )
>>     suffix
>>     varint( block_position )
>>
>> Index records use prefix compression exactly like `ref_record`.
>>
>> Index records store `block_position` after the suffix, specifying the
>> absolute position in bytes (from the start of the file) of the block
>> that ends with this reference.
>
> Is there a reason that the index lists the *last* refname that is
> contained in a block rather than the *first* refname? I can't think of a
> reason to choose one vs. the other, but your choice was initially
> surprising. I don't think it matters either way; I was just curious.

Yes, there is a reason. When a reader is searching the index block and
discovers a key that is greater than their search needle, they are now
sitting on a record with the block_position for that greater key. By
using the *last* refname the current block_position is the one to seek
to.

If instead we used *first* refname, the reader would now have to
backtrack to the prior index record to get the block_position out of
that record. Or it has to keep a running "prior_position" local
variable.

Using last simplifies the reader's code.


> Do I understand correctly that all `block_position`s are *byte*
> addresses, even in the `ref_index` where they should all be multiples of
> the block size (except the zeroth one)? I think that's OK, but note that
> it will waste more than a byte per `ref_index` and `obj_index` record,
> on average.

Yes, because it simplifies a lot of code, especially if we do away
with any sort of requirement for alignment.


>> Readers must examine the block header at `block_position` to determine
>> if the next block is another level index block, or the leaf-level ref
>> block.
>
> For scanning through a whole namespace, like `refs/tags/`, I guess you
> only need to use a binary search to find the beginning of the range.
> Then you would read serially forwards from there, continuing from one
> `ref_block` to the next, until you find a refname that doesn't start
> with `refs/tags/`. In other words, there is no reason to binary search
> to find the end of the namespace, correct?

Correct.


>> [...]
>> #### Importing logs
>>
>> When importing from `$GIT_DIR/logs` writers should globally order all
>> log records roughly by timestamp while preserving file order, and
>> assign unique, increasing `update_index` values for each log line.
>> Newer log records get higher `update_index` values.
>>
>> Although an import may write only a single reftable file, the reftable
>> file must span many unique `update_index`, as each log line requires
>> its own `update_index` to preserve semantics.
>
> Thinking out loud here: A really high-quality importer might want to
> group together, under the same `update_index`, ref updates that are
> thought originally to have been done in the same transaction.
[...]
> But I doubt that it is worth the effort. (The whole idea gives me nasty
> flashbacks from working on cvs2svn/cvs2git.)

Yup, that is why I didn't go down writing a description like that here. :)

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: reftable [v6]: new ref storage format
  2017-08-15 22:47 Shawn Pearce
@ 2017-08-18  9:24 ` Michael Haggerty
  0 siblings, 0 replies; 14+ messages in thread
From: Michael Haggerty @ 2017-08-18  9:24 UTC (permalink / raw)
  To: Shawn Pearce
  Cc: git, Jeff King, Junio C Hamano, David Borowitz, Stefan Beller

On Wed, Aug 16, 2017 at 12:47 AM, Shawn Pearce <spearce@spearce.org> wrote:
> On Mon, Aug 14, 2017 at 5:13 AM, Michael Haggerty <mhagger@alum.mit.edu> wrote:
>> On 08/07/2017 03:47 AM, Shawn Pearce wrote:
>>> 6th iteration of the reftable storage format.
> [...]
>>> #### index record
>>>
>>> An index record describes the last entry in another block.
>>> Index records are written as:
>>>
>>>     varint( prefix_length )
>>>     varint( (suffix_length << 3) | 0 )
>>>     suffix
>>>     varint( block_position )
>>>
>>> Index records use prefix compression exactly like `ref_record`.
>>>
>>> Index records store `block_position` after the suffix, specifying the
>>> absolute position in bytes (from the start of the file) of the block
>>> that ends with this reference.
>>
>> Is there a reason that the index lists the *last* refname that is
>> contained in a block rather than the *first* refname? I can't think of a
>> reason to choose one vs. the other, but your choice was initially
>> surprising. I don't think it matters either way; I was just curious.
>
> Yes, there is a reason. When a reader is searching the index block and
> discovers a key that is greater than their search needle, they are now
> sitting on a record with the block_position for that greater key. By
> using the *last* refname the current block_position is the one to seek
> to.
>
> If instead we used *first* refname, the reader would now have to
> backtrack to the prior index record to get the block_position out of
> that record. Or it has to keep a running "prior_position" local
> variable.
>
> Using last simplifies the reader's code.

Ah, OK. I was thinking of this as being a binary search, in which case
you *must* see both bracketing records before you are done, and the
chances are 50-50 which one you see first. But this search is a little
bit different, because the index records within a restart block have
to be scanned linearly. So it is much more likely that you see the
"before" record followed by the "after" record.

Thanks for the explanation.

Michael

^ permalink raw reply	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2017-08-18  9:24 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2017-08-07  1:47 reftable [v6]: new ref storage format Shawn Pearce
2017-08-07 18:27 ` Stefan Beller
2017-08-07 18:30   ` Shawn Pearce
2017-08-08 23:52     ` Stefan Beller
2017-08-08  7:28 ` Jeff King
2017-08-08 19:01 ` Junio C Hamano
2017-08-08 22:27   ` Shawn Pearce
2017-08-08 23:34     ` Junio C Hamano
2017-08-09  0:01       ` Shawn Pearce
2017-08-08 19:25 ` Junio C Hamano
2017-08-08 22:30   ` Shawn Pearce
2017-08-14 12:13 ` Michael Haggerty
  -- strict thread matches above, loose matches on Subject: below --
2017-08-15 22:47 Shawn Pearce
2017-08-18  9:24 ` Michael Haggerty

Code repositories for project(s) associated with this public inbox

	https://80x24.org/mirrors/git.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).