You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reftable.md 35KB

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