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 34KB

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