<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
      <follow_challenge>
        <feedId>67389382546394112</feedId>
        <userId>43486084483263488</userId>
      </follow_challenge>
      <title>Inhzus</title>
      <link>https://zunish.io</link>
      <description></description>
      <generator>Zola</generator>
      <language>en</language>
      <atom:link href="https://zunish.io/index.xml" rel="self" type="application/rss+xml"/>
      <lastBuildDate>Mon, 21 Sep 2026 00:00:00 +0000</lastBuildDate>
      <item>
          <title>Vespa: Filtered HNSW Search with ACORN-1</title>
          <pubDate>Mon, 21 Sep 2026 00:00:00 +0000</pubDate>
          <author>inhzus</author>
          <link>https://zunish.io/posts/2026-09-21-vespa-acorn-filtered-hnsw/</link>
          <guid>https://zunish.io/posts/2026-09-21-vespa-acorn-filtered-hnsw/</guid>
          <description xml:base="https://zunish.io/posts/2026-09-21-vespa-acorn-filtered-hnsw/">&lt;p&gt;&lt;em&gt;Note: This post was refined with AI assistance for clarity and structure.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Adding a category or access-control filter to an HNSW query creates a navigation problem. A document that cannot appear in the results may still connect two useful parts of the graph. Can the search follow its links without paying to calculate its vector distance?&lt;/p&gt;
&lt;p&gt;Vespa&#39;s ACORN-1-inspired traversal does this by exploring a neighborhood before scoring its matching nodes. It extends the search described in the &lt;a href=&quot;https://zunish.io/posts/2026-09-20-vespa-hnsw-index/&quot;&gt;HNSW index post&lt;/a&gt;; the implementation is introduced in &lt;a rel=&quot;external&quot; href=&quot;https://blog.vespa.ai/additions-to-hnsw/&quot;&gt;Additions to HNSW in Vespa&lt;/a&gt;. Source references use revision &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/tree/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2&quot;&gt;39bf68f4&lt;/a&gt;. As in the previous example, each document has one vector, so nodeid and local docid coincide.&lt;/p&gt;
&lt;h2 id=&quot;filtering-and-graph-connectivity&quot;&gt;Filtering and graph connectivity&lt;/h2&gt;
&lt;p&gt;Consider this path through a graph built before the filter was known:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;plain&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;1 (matches) --- 2 (rejected) --- 3 (matches)&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Skipping node 2 entirely cuts this route from 1 to 3. Reading node 2&#39;s links, however, lets the search discover node 3 without calculating node 2&#39;s distance. Node 3 can then compete for a place in the search queues.&lt;/p&gt;
&lt;p&gt;Ordinary filtered HNSW still calculates distances for rejected nodes and may put them in the exploration queue. Node 2 can therefore help the search reach node 3, but its vector must be loaded and scored along the way. With a restrictive filter, rejected vectors can account for much of that work.&lt;/p&gt;
&lt;p&gt;Post-filtering has a different limitation. Searching without the filter and removing rejected hits afterward can return too few results. Increasing the number of retrieved candidates helps, but does not guarantee that enough will pass.&lt;/p&gt;
&lt;h2 id=&quot;acorn-1&quot;&gt;ACORN-1&lt;/h2&gt;
&lt;p&gt;The 2024 &lt;a rel=&quot;external&quot; href=&quot;https://arxiv.org/abs/2403.04871&quot;&gt;ACORN paper&lt;/a&gt; studies search over the subgraph satisfying a query predicate. ACORN-1 uses the idea illustrated above: expand through one-hop and two-hop neighbors, apply the filter, and collect a bounded number of matching nodes for distance calculation.&lt;/p&gt;
&lt;p&gt;Vespa&#39;s graph construction differs from the paper&#39;s. The paper&#39;s ACORN-1 omits the usual HNSW neighbor-pruning heuristic. Vespa keeps its existing graph construction and applies the traversal to that graph, without building a denser graph or a separate index per filter.&lt;/p&gt;
&lt;p&gt;For the path above, the saving is node 2&#39;s vector load and distance calculation. The added work is reading its links and checking the filter on the nodes they lead to. Their relative cost determines whether the traversal is faster.&lt;/p&gt;
&lt;h2 id=&quot;exploring-a-neighborhood&quot;&gt;Exploring a neighborhood&lt;/h2&gt;
&lt;p&gt;The main change is in &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp#L453&quot;&gt;search_layer_filter_first_helper&lt;/a&gt;. The outer search still maintains a nearest-first candidate queue and a bounded collection of the best results. Before calculating distances, it calls &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp#L543&quot;&gt;exploreNeighborhood&lt;/a&gt; to collect nodes that pass the filter.&lt;/p&gt;
&lt;p&gt;The neighborhood search uses two deques:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;todo&lt;/code&gt;: nodeids whose links can be followed in the next hop, whether or not they pass the filter.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;found&lt;/code&gt;: previously unvisited nodes that pass the filter and should have their distances calculated.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Each call to &lt;code&gt;exploreNeighborhoodByOneHop&lt;/code&gt; processes only the entries already in &lt;code&gt;todo&lt;/code&gt; when the call begins. Neighbors appended during that call are left for the next hop. Matching nodes enter &lt;code&gt;found&lt;/code&gt;, and collection stops when its size reaches the layer&#39;s maximum link count.&lt;/p&gt;
&lt;p&gt;Starting from node 1 in the three-node path, the first hop encounters node 2. It fails the filter, so it contributes links for the next hop but no entry in &lt;code&gt;found&lt;/code&gt;. The second hop can discover node 3 and add it to &lt;code&gt;found&lt;/code&gt;, ready for distance calculation. This separates following a route from scoring every vector along it.&lt;/p&gt;
&lt;p&gt;The traversal can be simplified to:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;limit&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; max_links_for_level&lt;/span&gt;&lt;span&gt;(level);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;todo&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span&gt; {candidate.nodeid};&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;found&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span&gt; {};&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;explore_one_hop&lt;/span&gt;&lt;span&gt;(todo, found, limit);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;explore_one_hop&lt;/span&gt;&lt;span&gt;(todo, found, limit);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;if&lt;/span&gt;&lt;span&gt; (todo.&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;size&lt;/span&gt;&lt;span&gt;()&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; &amp;lt;&lt;/span&gt;&lt;span&gt; exploration&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; *&lt;/span&gt;&lt;span&gt; limit&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; *&lt;/span&gt;&lt;span&gt; limit) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;    explore_one_hop&lt;/span&gt;&lt;span&gt;(todo, found, limit);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After these calls, the caller calculates distances for &lt;code&gt;found&lt;/code&gt; and updates the search queues. Each neighborhood has its own collection limit, independent of the query&#39;s target hit count and overall search width.&lt;/p&gt;
&lt;p&gt;Both matching and rejected nodes can supply links for another hop. The visited tracker prevents repeated collection into &lt;code&gt;found&lt;/code&gt;, while &lt;code&gt;todo&lt;/code&gt; may contain repeated entries. Its size counts queued entries, which matters for the third-hop condition.&lt;/p&gt;
&lt;h3 id=&quot;a-third-hop&quot;&gt;A third hop&lt;/h3&gt;
&lt;p&gt;Two hops may still be insufficient when the filter leaves large gaps between matching nodes. A third hop can reach farther, but its cost grows quickly. With &lt;code&gt;max-links-per-node = 16&lt;/code&gt;, level 0 permits 32 links per node; unrestricted three-hop expansion could encounter up to &lt;code&gt;32 * 32 * 32 = 32768&lt;/code&gt; link paths before accounting for overlap.&lt;/p&gt;
&lt;p&gt;Vespa only attempts the third hop when the remaining &lt;code&gt;todo&lt;/code&gt; is smaller than &lt;code&gt;exploration * limit * limit&lt;/code&gt;. The same &lt;code&gt;found&lt;/code&gt; limit still applies. Increasing &lt;code&gt;exploration&lt;/code&gt; allows the extra hop in more neighborhoods, potentially improving recall at the cost of more traversal.&lt;/p&gt;
&lt;h2 id=&quot;selecting-the-search-path&quot;&gt;Selecting the search path&lt;/h2&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp#L196&quot;&gt;NearestNeighborBlueprint&lt;/a&gt; compares the filter&#39;s hit ratio with &lt;code&gt;filter-first-threshold&lt;/code&gt;. Here, hit ratio means the fraction of documents that pass: a smaller value means a more restrictive filter. When filtered approximate search is selected and the ratio is below the threshold, it requests the filter-first traversal.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp#L1077&quot;&gt;top_k_candidates&lt;/a&gt; uses the filter-first traversal only at level 0. Upper-level navigation and entry-point scoring still calculate distances as before. A rejected entry point leaves the result collection but can seed exploration; subsequent neighborhood expansions skip scoring the rejected neighbors they discover.&lt;/p&gt;
&lt;p&gt;When sufficiently few documents pass, the planner can choose exact search instead: a restrictive filter directly reduces the number of vectors it must score. Filter-first traversal is used within the approximate-search path, after that choice.&lt;/p&gt;
&lt;h2 id=&quot;parameters-and-trade-offs&quot;&gt;Parameters and trade-offs&lt;/h2&gt;
&lt;p&gt;The &lt;a rel=&quot;external&quot; href=&quot;https://docs.vespa.ai/en/reference/api/query.html#ranking.matching.filterFirstThreshold&quot;&gt;query API documentation&lt;/a&gt;, checked on September 21, 2026, lists these defaults:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Query parameter&lt;/th&gt;&lt;th&gt;Default&lt;/th&gt;&lt;th&gt;Effect&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;ranking.matching.filterFirstThreshold&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;0.2&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Select filter-first traversal below this hit ratio, when using filtered graph search&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;ranking.matching.filterFirstExploration&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;0.01&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Control when to attempt three-hop expansion&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Their rank-profile equivalents are &lt;code&gt;filter-first-threshold&lt;/code&gt; and &lt;code&gt;filter-first-exploration&lt;/code&gt;. The 2025 blog post listed defaults of &lt;code&gt;0.0&lt;/code&gt; and &lt;code&gt;0.30&lt;/code&gt;; those values have since changed.&lt;/p&gt;
&lt;p&gt;The same hit ratio can produce different search costs. Matching nodes clustered near the query leave little wasted distance work for ACORN-1 to remove. Scattered matches can make extended neighborhoods useful. Matches far from the query&#39;s natural path may still be missed by bounded expansion.&lt;/p&gt;
&lt;p&gt;Measure latency at the same recall, and record both the filter hit ratio and its correlation with the query. Vespa tracks visited nodes and computed distances separately; looking at both helps explain where the time goes. A lower distance count alone does not establish a faster search: reaching node 3 without scoring node 2 still required reading node 2&#39;s links.&lt;/p&gt;
</description>
      </item>
      <item>
          <title>Vespa: Distributors and Buckets</title>
          <pubDate>Sun, 20 Sep 2026 00:00:00 +0000</pubDate>
          <author>inhzus</author>
          <link>https://zunish.io/posts/2026-09-20-vespa-distributor-and-buckets/</link>
          <guid>https://zunish.io/posts/2026-09-20-vespa-distributor-and-buckets/</guid>
          <description xml:base="https://zunish.io/posts/2026-09-20-vespa-distributor-and-buckets/">&lt;p&gt;&lt;em&gt;Note: This post was refined with AI assistance for clarity and structure.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Where does a document go after a client sends it to Vespa? The request first needs an owner distributor, then storage nodes for its replicas. Both decisions start with the document&#39;s bucket, but they can lead to different nodes.&lt;/p&gt;
&lt;p&gt;In the &lt;a href=&quot;https://zunish.io/posts/2024-10-12-vespa-vs-elasticsearch/&quot;&gt;Vespa comparison&lt;/a&gt;, I briefly mentioned bucket-based distribution. Following one Put makes the division of work clearer: the distributor tracks the copies, while the content nodes hold the documents. That distinction also explains what must be recovered when either one fails. Source references use Vespa revision &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/tree/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2&quot;&gt;39bf68f4&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;feeding-a-document&quot;&gt;Feeding a document&lt;/h2&gt;
&lt;p&gt;The example uses an indexed content cluster with six content nodes and corresponding distributors, a flat distribution, 16 distribution bits, and redundancy 2. The document is &lt;code&gt;id:news:article::kitten-finds-home-2024&lt;/code&gt;. Assume D3 owns its bucket and nodes 0 and 1 hold the replicas; these placements and the bucket values below are illustrative.&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;plain&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;Client&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;  -&amp;gt; Container: document processing and routing&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;  -&amp;gt; Owner distributor: resolve bucket and replicas&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;  -&amp;gt; Content nodes: apply the document operation&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;  -&amp;gt; Replies return through the distributor&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;components&quot;&gt;Components&lt;/h3&gt;
&lt;p&gt;A bucket is a group of documents whose ids share a number of low-order bits. It is the unit used for replica management, splitting, joining, and much of the storage-side synchronization.&lt;/p&gt;
&lt;p&gt;A distributor handles document operations for a subset of the buckets. It keeps metadata about their replicas and sends operations to the appropriate content nodes. The documents themselves are stored on those nodes, so a distributor can reconstruct its bucket database after a restart.&lt;/p&gt;
&lt;p&gt;The distributor and storage replicas are selected separately:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Mapping&lt;/th&gt;&lt;th&gt;Result&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Bucket to distributor&lt;/td&gt;&lt;td&gt;The owner that handles document operations&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Bucket to storage nodes&lt;/td&gt;&lt;td&gt;The nodes that should hold its replicas&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Both mappings use the distribution algorithm. The owner can handle operations for a bucket whose replicas are stored on other nodes.&lt;/p&gt;
&lt;p&gt;The Put goes through D3 to the two storage copies. The diagram&#39;s rows only organize this flat cluster; in a grouped configuration, each row shown would instead hold a full dataset copy.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-distributors-and-buckets/cluster-overview.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-distributors-and-buckets/cluster-overview.svg&quot; alt=&quot;Six nodes in two rows of three, with highlighted Put arrows from the container through owner D3 to bucket A&amp;#39;s copies inside proton on nodes 0 and 1. Other components are muted. Each row contains sample buckets A through F once. In the flat cluster, rows only organize the drawing; in a grouped variant, each row represents one replica group holding a full dataset copy.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;bucketid&quot;&gt;BucketId&lt;/h3&gt;
&lt;p&gt;Routing starts by turning the document id into a bucket id. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/document/src/vespa/document/bucket/bucketidfactory.cpp&quot;&gt;BucketIdFactory&lt;/a&gt; constructs a 64-bit value with this layout, from the most significant bit to the least significant bit:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;plain&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;63        58 57                      32 31                     0&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;+-----------+--------------------------+------------------------+&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;| used bits |       GID-derived bits   |        location        |&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;|  6 bits   |          26 bits         |        32 bits         |&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;+-----------+--------------------------+------------------------+&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The top six bits say how many of the remaining 58 bits identify the bucket. For example, a bucket with 16 used bits contains documents with the same lowest 16 bits. Increasing the count gives a smaller set of documents.&lt;/p&gt;
&lt;p&gt;For an ordinary id such as &lt;code&gt;id:news:article::kitten-finds-home-2024&lt;/code&gt;, the location is derived from the MD5 hash of its namespace-specific part, &lt;code&gt;kitten-finds-home-2024&lt;/code&gt;. The &lt;code&gt;n=&lt;/code&gt; and &lt;code&gt;g=&lt;/code&gt; schemes can override the location to co-locate related documents. The remaining bucket bits are derived from the document&#39;s global id. The details are in &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/document/src/vespa/document/base/idstring.cpp#L155&quot;&gt;IdString&lt;/a&gt;, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/document/src/vespa/document/base/documentid.cpp#L40&quot;&gt;DocumentId&lt;/a&gt;, and the bucket factory.&lt;/p&gt;
&lt;p&gt;The factory returns a full 58-bit identifier, which the distributor resolves to an existing ancestor bucket, usually with fewer used bits.&lt;/p&gt;
&lt;p&gt;Since documents in a bucket share the low-order bits, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/document/src/vespa/document/bucket/bucketid.h#L125&quot;&gt;BucketId::toKey&lt;/a&gt; reverses the data bits and retains the used-bit count in the database key. This keeps related buckets together for parent/child lookups.&lt;/p&gt;
&lt;h3 id=&quot;distribution&quot;&gt;Distribution&lt;/h3&gt;
&lt;p&gt;Given the same bucket, cluster state, and configuration, the &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/vdslib/src/vespa/vdslib/distribution/distribution.cpp#L352&quot;&gt;distribution algorithm&lt;/a&gt; computes the same ideal nodes. Nodes therefore do not need to ask a separate service for every bucket&#39;s placement.&lt;/p&gt;
&lt;p&gt;For a flat cluster, the process is roughly:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Check that the bucket uses at least as many bits as the cluster&#39;s distribution bit count.&lt;/li&gt;
&lt;li&gt;Derive a random seed from the bucket id.&lt;/li&gt;
&lt;li&gt;Generate a deterministic score for each eligible node, adjusting for its capacity.&lt;/li&gt;
&lt;li&gt;Select the highest-scoring nodes up to the required replica count.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Hierarchical configurations first select replica groups, then nodes within those groups.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;getIdealDistributorNode&lt;/code&gt; selects one distributor. &lt;code&gt;getIdealStorageNodes&lt;/code&gt; selects the storage replicas. Their seeds are related, but the storage seed can incorporate additional high-order bucket bits after sufficiently deep splitting.&lt;/p&gt;
&lt;h3 id=&quot;finding-the-distributor&quot;&gt;Finding the distributor&lt;/h3&gt;
&lt;p&gt;After document processing, the MessageBus &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/ContentPolicy.java&quot;&gt;ContentPolicy&lt;/a&gt; calculates the bucket id and uses its cached cluster state to select the owner distributor. The request is addressed directly to that distributor.&lt;/p&gt;
&lt;p&gt;The receiving distributor checks ownership again. If the client&#39;s cluster state is stale, the request can receive &lt;code&gt;WrongDistribution&lt;/code&gt;, carrying state information that lets routing retry. A distributor losing ownership in a pending state can also return &lt;code&gt;BUSY&lt;/code&gt; during the transition.&lt;/p&gt;
&lt;h3 id=&quot;selecting-replicas&quot;&gt;Selecting replicas&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/distributor/operations/external/putoperation.cpp&quot;&gt;PutOperation&lt;/a&gt; resolves the full document bucket id to an existing bucket in the database. If none exists, it can create an appropriate bucket using the configured minimum split depth.&lt;/p&gt;
&lt;h4 id=&quot;ideal-state-and-current-state&quot;&gt;Ideal state and current state&lt;/h4&gt;
&lt;p&gt;The ideal nodes are where the replicas should be. The bucket database records where replicas currently exist and what is known about them. During failures or redistribution, these can differ.&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/bucketdb/btree_bucket_database.h&quot;&gt;bucket database&lt;/a&gt; uses a B-tree with single-writer/multiple-reader access. Each bucket entry records replica metadata, including node index, timestamp, checksum, document count, and size. It also records flags such as &lt;code&gt;trusted&lt;/code&gt; and &lt;code&gt;active&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;trusted&lt;/code&gt; records the distributor&#39;s assessment of replica consistency, using metadata such as checksum and document count. &lt;code&gt;active&lt;/code&gt; determines whether the copy participates in search; the activation policy also depends on the cluster&#39;s group configuration.&lt;/p&gt;
&lt;p&gt;Storage replies and bucket-info requests update this metadata. Each distributor &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/distributor/distributor_stripe.h&quot;&gt;stripe&lt;/a&gt; owns a disjoint subset of buckets and sequences writes to its database, allowing the process to work across multiple stripes.&lt;/p&gt;
&lt;p&gt;During redistribution, some replicas may still be on their old nodes. Target selection accounts for those existing copies along with ideal placement.&lt;/p&gt;
&lt;p&gt;For our bucket, D3 sends bucket operations and Put commands to nodes 0 and 1.&lt;/p&gt;
&lt;h3 id=&quot;applying-the-write&quot;&gt;Applying the write&lt;/h3&gt;
&lt;p&gt;Each target now applies the Put. Its storage service layer coordinates the operation with bucket locking and dispatches it through the persistence SPI. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/persistence/asynchandler.cpp#L144&quot;&gt;AsyncHandler::handlePut&lt;/a&gt; eventually calls the provider&#39;s &lt;code&gt;putAsync&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For indexed storage, the service layer runs inside the searchnode process. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/apps/proton/proton.cpp#L178&quot;&gt;ProtonServiceLayerProcess::getProvider&lt;/a&gt; returns proton&#39;s persistence engine, so this handoff is an in-process call.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcore/proton/persistenceengine/persistenceengine.cpp#L305&quot;&gt;PersistenceEngine::putAsync&lt;/a&gt; finds the document-type handler and forwards the operation. Further down, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcore/proton/server/feedhandler.cpp#L144&quot;&gt;FeedHandler::performPut&lt;/a&gt; prepares it, appends it to the transaction log, and passes it to the feed view. Attribute, index, and document-store work is then handled by the relevant parts of proton.&lt;/p&gt;
&lt;p&gt;The different index structures are updated separately. Their concurrency mechanisms protect individual accesses, but a search overlapping an unfinished write can observe partially applied changes. See &lt;a href=&quot;https://zunish.io/posts/2026-09-20-vespa-storage-engine-thread-safety/&quot;&gt;the thread-safety post&lt;/a&gt; for the implementation.&lt;/p&gt;
&lt;h3 id=&quot;returning-the-result&quot;&gt;Returning the result&lt;/h3&gt;
&lt;p&gt;Storage replies carry updated bucket information, which the distributor incorporates into its database. The reply tracker also decides when to return the client response.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/distributor/persistencemessagetracker.cpp#L116&quot;&gt;PersistenceMessageTracker&lt;/a&gt; normally waits for the outstanding messages to finish. Early acknowledgement can let the client proceed sooner: it depends on the configured initial redundancy and may also require completion of the primary target. Our redundancy of 2 specifies the replica count; the acknowledgement settings determine when the response can return.&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;external&quot; href=&quot;https://docs.vespa.ai/en/content/consistency.html#write-durability-and-consistency&quot;&gt;consistency documentation&lt;/a&gt; describes the external guarantee: acknowledged writes are durable, and search changes are visible after a successful response by default. A configured visibility delay changes the latter behavior. A failed response can still mean that some replicas applied the write.&lt;/p&gt;
&lt;h2 id=&quot;search-requests&quot;&gt;Search requests&lt;/h2&gt;
&lt;p&gt;The search path is shorter:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;plain&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;Container -&amp;gt; Searchnodes -&amp;gt; Container&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The container dispatches queries to searchnodes and merges their results. Distributors are not part of this request path. They do affect search availability indirectly by maintaining which bucket copies are active.&lt;/p&gt;
&lt;p&gt;In the standard &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java#L547&quot;&gt;content-node configuration&lt;/a&gt;, a storage node and its distributor share a host and distribution key, with a searchnode associated with the storage node.&lt;/p&gt;
&lt;p&gt;The &lt;a href=&quot;https://zunish.io/posts/2025-05-26-vespa-matching-top-to-down/&quot;&gt;matching overview&lt;/a&gt; covers the query side in more detail.&lt;/p&gt;
&lt;h2 id=&quot;maintaining-replicas&quot;&gt;Maintaining replicas&lt;/h2&gt;
&lt;p&gt;The Put has finished, but D3 still has work to do for this bucket. Its replicas may grow, diverge, or need to move after a cluster-state change. The distributor repeatedly compares its bucket database with ideal state. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/distributor/idealstatemanager.cpp&quot;&gt;IdealStateManager&lt;/a&gt; runs an ordered set of checkers:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Checker&lt;/th&gt;&lt;th&gt;Work&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Bucket state&lt;/td&gt;&lt;td&gt;Activate or deactivate replicas&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Split bucket&lt;/td&gt;&lt;td&gt;Split buckets exceeding configured limits&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Split inconsistency&lt;/td&gt;&lt;td&gt;Reconcile inconsistent split layouts&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Synchronize and move&lt;/td&gt;&lt;td&gt;Merge divergent replicas and move data toward ideal placement&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Join buckets&lt;/td&gt;&lt;td&gt;Join eligible small buckets&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Extra copies&lt;/td&gt;&lt;td&gt;Remove excess replicas&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Garbage collection&lt;/td&gt;&lt;td&gt;Remove documents matching configured expiry rules&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;The first applicable checker in the configured order supplies the selected maintenance result. The code still runs the remaining checkers to collect statistics.&lt;/p&gt;
&lt;p&gt;A merge synchronizes the timestamped documents held by replicas. Moving a bucket can use the same mechanism: create a copy at the destination, merge the data into it, then remove an unnecessary old copy. The actual transfer therefore takes time even though calculating the new ideal nodes is inexpensive.&lt;/p&gt;
&lt;h3 id=&quot;splitting-and-joining&quot;&gt;Splitting and joining&lt;/h3&gt;
&lt;p&gt;As documents accumulate, large buckets make replica operations more expensive. Very small buckets incur more metadata overhead. Splitting and joining balance these costs.&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/config/stor-distributormanager.def&quot;&gt;distributor configuration&lt;/a&gt; defines separate size and document-count limits. In this revision, the low-level split defaults are 16 MB and 1024 documents; the join defaults are 16 MB and 512 documents. For a running cluster, use its generated configuration to determine the effective limits.&lt;/p&gt;
&lt;p&gt;A split can be triggered while processing a Put, by a background size/count check, by an inconsistent split layout, or by the need to reach the cluster&#39;s minimum distribution depth. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/distributor/operations/idealstate/splitoperation.cpp&quot;&gt;SplitOperation&lt;/a&gt; sends commands to replicas and updates the database from their replies.&lt;/p&gt;
&lt;h4 id=&quot;parent-and-child-buckets&quot;&gt;Parent and child buckets&lt;/h4&gt;
&lt;p&gt;Suppose our bucket uses 16 bits and its location is &lt;code&gt;0x2717&lt;/code&gt;. Both nodes 0 and 1 split their copy by one additional bit:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-distributors-and-buckets/bucket-split.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-distributors-and-buckets/bucket-split.svg&quot; alt=&quot;A parent bucket with the low 16 bits 0x2717 splits into 17-bit children 0x02717 and 0x12717, distinguished by bit 16. On both replica nodes, the parent is replaced by both children, leaving two copies of each child.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The two children differ at bit 16, counting from zero. Each document goes to the child matching that bit in its full identifier.&lt;/p&gt;
&lt;p&gt;Splitting this 16-bit bucket into 17-bit children leaves the placement seed unchanged when the distribution bit count stays the same. In this revision, extra storage-seed mixing begins only above 33 used bits. A split therefore need not change the ideal nodes.&lt;/p&gt;
&lt;p&gt;The split partitions documents on the nodes holding the parent. If the resulting placement requires migration, separate maintenance work moves the replicas.&lt;/p&gt;
&lt;p&gt;Joining combines suitable small buckets. Both operations must coordinate the distributor&#39;s metadata with the content nodes while accounting for requests already in flight under the old bucket layout.&lt;/p&gt;
&lt;h3 id=&quot;when-a-node-fails&quot;&gt;When a node fails&lt;/h3&gt;
&lt;p&gt;Return to the two copies on nodes 0 and 1. If node 0 fails, node 1 still holds the documents. Once the cluster controller marks node 0 unavailable and publishes a new state, distributors recalculate ownership and placement. The bucket database transition removes unavailable copies from the usable view and incorporates information gathered for the new state.&lt;/p&gt;
&lt;p&gt;If a surviving searchable copy needs activation, maintenance schedules it. Search coverage can be reduced during this period, and losing every copy of a bucket cannot be repaired from metadata alone.&lt;/p&gt;
&lt;p&gt;Suppose the new ideal targets are nodes 1 and 2. Synchronization can copy the surviving data to node 2 and restore redundancy. Write availability during recovery depends on the cluster state and available targets, rather than a fixed majority rule.&lt;/p&gt;
&lt;p&gt;During ownership transfer, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/distributor/externaloperationhandler.cpp&quot;&gt;ExternalOperationHandler&lt;/a&gt; can reject writes with &lt;code&gt;STALE_TIMESTAMP&lt;/code&gt; before the configured safe time. This timing constraint accounts for operations associated with the previous owner while the transition settles; it does not establish strong consistency.&lt;/p&gt;
&lt;h3 id=&quot;when-only-a-distributor-fails&quot;&gt;When only a distributor fails&lt;/h3&gt;
&lt;p&gt;If only D3 fails, both storage copies can remain on nodes 0 and 1. The new cluster state assigns D3&#39;s buckets to other distributors; suppose D5 becomes the owner of this one. It needs to gather bucket information from the storage nodes to rebuild its metadata.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/storage/src/vespa/storage/distributor/stripe_bucket_db_updater.cpp&quot;&gt;StripeBucketDBUpdater&lt;/a&gt; handles this transition. The old owner drops buckets it no longer owns, while the new owner incorporates reports from storage nodes. Requests may be retried while this is happening.&lt;/p&gt;
&lt;p&gt;With storage placement unchanged, recovery requires rebuilding the owner&#39;s view of the bucket. Losing a storage copy requires document transfer as well:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-distributors-and-buckets/failure-recovery.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-distributors-and-buckets/failure-recovery.svg&quot; alt=&quot;Before, transition, and recovered views for bucket A. A distributor-only failure transfers ownership from D3 to D5 through bucket metadata reports while copies remain on nodes 0 and 1. A storage-node failure leaves a surviving copy on node 1; the new ideal targets are nodes 1 and 2, and document synchronization restores the second copy on node 2.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Dashed arrows: metadata. Green arrow: document transfer.&lt;/em&gt;&lt;/p&gt;
</description>
      </item>
      <item>
          <title>Vespa: HNSW Index Implementation</title>
          <pubDate>Sun, 20 Sep 2026 00:00:00 +0000</pubDate>
          <author>inhzus</author>
          <link>https://zunish.io/posts/2026-09-20-vespa-hnsw-index/</link>
          <guid>https://zunish.io/posts/2026-09-20-vespa-hnsw-index/</guid>
          <description xml:base="https://zunish.io/posts/2026-09-20-vespa-hnsw-index/">&lt;p&gt;&lt;em&gt;Note: This post was refined with AI assistance for clarity and structure.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The previous &lt;a href=&quot;https://zunish.io/posts/2024-12-04-vespa-index-impl/&quot;&gt;index implementation post&lt;/a&gt; left tensors for later. Vector search adds a graph alongside the attribute values: a query follows its links to find promising vectors, and a writer changes those links as documents arrive or disappear.&lt;/p&gt;
&lt;p&gt;Five documents are enough to trace the full path from graph storage to search queues. The same arrays also show why changing a neighbor list requires more than overwriting its contents. Source links point to Vespa revision &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/tree/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2&quot;&gt;39bf68f4&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;
&lt;p&gt;Vespa separates the graph from the vectors. &lt;code&gt;HnswGraph&lt;/code&gt; stores nodes and their connections, while &lt;code&gt;TensorAttribute&lt;/code&gt; provides the vector values used to calculate distances. &lt;code&gt;HnswIndex&lt;/code&gt; implements insertion, search, and removal on top of these two parts.&lt;/p&gt;
&lt;p&gt;There are two variants:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;SINGLE&lt;/code&gt;: one vector per document. The graph node id is the document&#39;s local id, so no extra mapping is needed.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;MULTI&lt;/code&gt;: several vector subspaces per document. Each subspace gets a graph node, and the implementation maintains the mapping between document ids and node ids.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For &lt;code&gt;MULTI&lt;/code&gt;, the mapping records both docid and subspace so distance calculation can find the vector in the attribute&#39;s value store. The result collection accounts for multiple graph nodes belonging to the same document.&lt;/p&gt;
&lt;p&gt;The example uses &lt;code&gt;SINGLE&lt;/code&gt;. Docid below means the local document id on one searchnode.&lt;/p&gt;
&lt;h2 id=&quot;example&quot;&gt;A five-document graph&lt;/h2&gt;
&lt;p&gt;Take five documents with one two-dimensional vector each and &lt;code&gt;M = max-links-per-node = 2&lt;/code&gt;. Level 0 permits up to four links per node; higher levels permit two. This graph is illustrative, rather than the output of a particular insertion sequence.&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;docid&lt;/th&gt;&lt;th&gt;Vector&lt;/th&gt;&lt;th&gt;Highest level&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;(0, 0)&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;2&lt;/td&gt;&lt;td&gt;(1, 0)&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;(0, 1)&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;(1, 1)&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;(2, 2)&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;In normal insertion, the highest level is drawn by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/inv_log_level_generator.h&quot;&gt;InvLogLevelGenerator&lt;/a&gt;. The probability of level &lt;code&gt;k&lt;/code&gt; is &lt;code&gt;(1/M)^k * (1 - 1/M)&lt;/code&gt;. Here we simply choose the levels shown above.&lt;/p&gt;
&lt;p&gt;Node 5 is the entry point at level 2. The amber path shows the upper-level descent for query &lt;code&gt;(0.8, 0.9)&lt;/code&gt;, which we will follow after unpacking the storage layout.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-hnsw-index-implementation/graph-levels.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-hnsw-index-implementation/graph-levels.svg&quot; alt=&quot;Three graph levels: level 2 contains entry node 5; level 1 connects nodes 1 and 5; level 0 has bidirectional links 1–2, 1–3, 1–5, 2–4, 3–4, and 4–5. The highlighted search descends from node 5 at level 2, moves from 5 to 1 at level 1, and descends to node 1 at level 0.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The completed graph has reverse edges and stays within the link limits. During an update, a concurrent reader may see one direction change before the other.&lt;/p&gt;
&lt;h2 id=&quot;graph-storage&quot;&gt;Graph storage&lt;/h2&gt;
&lt;p&gt;To follow a link out of node 5, the query first needs its level array, then that level&#39;s neighbor array. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_graph.h&quot;&gt;HnswGraph&lt;/a&gt; stores these separately:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;NodeVector nodes;&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;                         // nodeid -&amp;gt; levels ref&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;LevelArrayStore levels_store;&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;             // array of link refs per node&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;LinkArrayStore links_store;&lt;/span&gt;&lt;span style=&quot;color: #6A737D;&quot;&gt;               // array of neighbor nodeids&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;std&lt;/span&gt;&lt;span&gt;::atomic&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;&amp;lt;uint64_t&amp;gt;&lt;/span&gt;&lt;span&gt; entry_nodeid_and_level;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The graph also holds counters and a generation handler for reclaiming replaced storage.&lt;/p&gt;
&lt;h3 id=&quot;nodes&quot;&gt;Nodes&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;nodes&lt;/code&gt; is an &lt;code&gt;RcuVector&lt;/code&gt;, indexed by nodeid. For &lt;code&gt;SINGLE&lt;/code&gt;, each element is an &lt;code&gt;HnswSimpleNode&lt;/code&gt;, which holds only an &lt;code&gt;AtomicEntryRef&lt;/code&gt; pointing into &lt;code&gt;levels_store&lt;/code&gt;. Node 0 is reserved.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/vespalib/src/vespa/vespalib/datastore/atomic_entry_ref.h&quot;&gt;AtomicEntryRef&lt;/a&gt; wraps a &lt;code&gt;std::atomic&amp;lt;uint32_t&amp;gt;&lt;/code&gt; encoding a buffer id and offset. Resolving that reference locates the array within the store.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;MULTI&lt;/code&gt; variant uses &lt;code&gt;HnswNode&lt;/code&gt;, which additionally stores the document id and subspace id described above.&lt;/p&gt;
&lt;h3 id=&quot;levels-and-links&quot;&gt;Levels and links&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;levels_store&lt;/code&gt; is an &lt;code&gt;ArrayStore&amp;lt;AtomicEntryRef&amp;gt;&lt;/code&gt;. Node 5 occupies levels 0 through 2, so its level array has three entries, each referring to the neighbor array for one level.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;links_store&lt;/code&gt; is an &lt;code&gt;ArrayStore&amp;lt;uint32_t&amp;gt;&lt;/code&gt;. Its arrays contain only neighbor nodeids.&lt;/p&gt;
&lt;p&gt;The two stores use different &lt;code&gt;EntryRef&lt;/code&gt; layouts. The level store reserves 10 bits for the buffer id and 22 for the offset; the link store uses 12 and 20 respectively. This gives them 1024 and 4096 possible buffers.&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/default_nearest_neighbor_index_factory.cpp&quot;&gt;factory&lt;/a&gt; sets the link limits used in our example: &lt;code&gt;2 * M&lt;/code&gt; at level 0 and &lt;code&gt;M&lt;/code&gt; above it. Insertion may temporarily exceed a limit before pruning the neighbor list.&lt;/p&gt;
&lt;h3 id=&quot;in-memory&quot;&gt;In memory&lt;/h3&gt;
&lt;p&gt;For node 5, the first lookup reaches its three-entry level array. The second reaches a neighbor array: &lt;code&gt;[1, 4]&lt;/code&gt; at level 0, &lt;code&gt;[1]&lt;/code&gt; at level 1, or &lt;code&gt;[]&lt;/code&gt; at level 2.&lt;/p&gt;
&lt;p&gt;Those arrays give the query nodeids to visit. Calculating a distance requires a separate lookup of the corresponding vector in &lt;code&gt;TensorAttribute&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-hnsw-index-implementation/graph-storage.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-hnsw-index-implementation/graph-storage.svg&quot; alt=&quot;The node vector contains level references, with node 0 invalid. Node 5&amp;#39;s EntryRef resolves to a three-entry level array. Its level 0, 1, and 2 references resolve to neighbor arrays [1, 4], [1], and [] respectively. TensorAttribute separately holds the vector (2, 2) for docid 5.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Across the example graph, 14 neighbor ids take 56 bytes. The full memory footprint also includes the node vector, level references, spare buffer capacity, allocator metadata, and retired storage awaiting reclamation.&lt;/p&gt;
&lt;p&gt;&lt;span id=&quot;query-planning-and-persistence&quot;&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index_saver.cpp&quot;&gt;HnswIndexSaver&lt;/a&gt; and its loader save and restore the graph as part of attribute persistence; the tensor values have their own storage.&lt;/p&gt;
&lt;h3 id=&quot;entry-point&quot;&gt;Entry point&lt;/h3&gt;
&lt;p&gt;Our query starts at node 5 on level 2. The entry point&#39;s nodeid and level are packed into one 64-bit atomic value:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;plain&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;63                         32 31                          0&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;+----------------------------+----------------------------+&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;|            level           |           nodeid           |&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;+----------------------------+----------------------------+&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;get_entry_node()&lt;/code&gt; reads this value, acquires the node&#39;s levels reference, then checks the entry point again. If the observations are incompatible, it retries. This handles an entry point being changed or removed while another thread starts a search.&lt;/p&gt;
&lt;h2 id=&quot;searching&quot;&gt;Following the query&lt;/h2&gt;
&lt;p&gt;For query &lt;code&gt;(0.8, 0.9)&lt;/code&gt; and top-k 2, the squared Euclidean distances to our five documents are:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;docid&lt;/th&gt;&lt;th&gt;Squared distance&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;1.45&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;2&lt;/td&gt;&lt;td&gt;0.85&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;0.65&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;0.05&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;2.65&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Squared distances preserve the ordering without square roots. The upper-level path in the graph diagram starts at node 5, moves to node 1 at level 1, and enters level 0 there.&lt;/p&gt;
&lt;p&gt;At level 0, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp#L364&quot;&gt;search_layer_helper&lt;/a&gt; keeps a nearest-first candidate queue and a bounded result collection. The candidate queue supplies the next node to expand; the result collection retains the best nodes found so far.&lt;/p&gt;
&lt;p&gt;For this example, assume the result collection holds two nodes, with no filter, no extra exploration slack, and no deadline reached:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-hnsw-index-implementation/search-queues.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-hnsw-index-implementation/search-queues.svg&quot; alt=&quot;Level-0 search trace, showing nodeid and squared distance. Seed 1 puts 1 at 1.45 in both collections. Expanding 1 gives candidates and results 3 at 0.65 and 2 at 0.85. Expanding 3 gives candidates 4 at 0.05 and 2 at 0.85, but retains results 4 and 3. Expanding 4 leaves 2 queued. The search stops before expanding 2 because 0.85 exceeds the worst retained distance, 0.65; the results remain 4 and 3.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;After expanding node 3, the results contain 4 and 3, but node 2 is still queued for exploration. Expanding node 4 does not improve the results, so the search stops before expanding 2: its distance, 0.85, exceeds the worst retained distance, 0.65. Documents 4 and 3 happen to be the exact nearest neighbors here. On a larger graph, the search width limits exploration, and the result remains approximate.&lt;/p&gt;
&lt;p&gt;This trace assumes the planner chose an unfiltered graph search. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp&quot;&gt;NearestNeighborBlueprint&lt;/a&gt; also considers exact search and filtered traversal based on the query, filter estimate, and configuration. The &lt;a href=&quot;https://zunish.io/posts/2026-09-21-vespa-acorn-filtered-hnsw/&quot;&gt;ACORN post&lt;/a&gt; follows what changes when some graph nodes fail a filter.&lt;/p&gt;
&lt;h2 id=&quot;updating-the-graph&quot;&gt;Updating the graph&lt;/h2&gt;
&lt;h3 id=&quot;replacing-a-neighbor-array&quot;&gt;Replacing a neighbor array&lt;/h3&gt;
&lt;p&gt;Node 5&#39;s level-0 reference currently resolves to &lt;code&gt;[1, 4]&lt;/code&gt;. Suppose a query has acquired that array when the writer needs to publish a different neighbor list. Overwriting the two entries would change memory the query is still reading.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_graph.cpp#L78&quot;&gt;set_link_array&lt;/a&gt; allocates a replacement and changes the reference in node 5&#39;s level array. Simplified:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;auto&lt;/span&gt;&lt;span&gt; new_ref&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span&gt; links_store.&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;add&lt;/span&gt;&lt;span&gt;(new_links);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;auto&lt;/span&gt;&lt;span&gt; old_ref&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span&gt; levels[level].&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;load_relaxed&lt;/span&gt;&lt;span&gt;();&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;levels[level].&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;store_release&lt;/span&gt;&lt;span&gt;(new_ref);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;links_store.&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;remove&lt;/span&gt;&lt;span&gt;(old_ref);&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The reader that already acquired &lt;code&gt;[1, 4]&lt;/code&gt; can finish with that array. A reader acquiring the newly published reference gets &lt;code&gt;new_links&lt;/code&gt;. Here &lt;code&gt;remove&lt;/code&gt; retires the old storage through the generation mechanism; its memory remains available while the appropriate generation guards are held.&lt;/p&gt;
&lt;p&gt;A query can encounter links published at different times as it moves between nodes. The guard protects the storage it reads, without freezing the whole graph. The &lt;a href=&quot;https://zunish.io/posts/2026-09-20-vespa-storage-engine-thread-safety/&quot;&gt;thread-safety post&lt;/a&gt; explains publication and reclamation in more detail.&lt;/p&gt;
&lt;h3 id=&quot;insertion&quot;&gt;Insertion&lt;/h3&gt;
&lt;p&gt;Inserting another document starts with the same kind of descent and neighborhood search as our query, after choosing a level for the new node. The search supplies candidate neighbors at the relevant levels. Neighbor selection can reject a candidate when it is closer to an already-selected neighbor than to the new node, avoiding links concentrated in nearly the same part of the graph.&lt;/p&gt;
&lt;p&gt;The writer then creates the node, connects it to the selected neighbors, adds reverse links, and prunes lists that exceed their limits. If the new node reaches a higher level than the current entry point, the entry point is updated. See &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp#L704&quot;&gt;the insertion implementation&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The expensive search for neighbors can run before the write phase. &lt;code&gt;prepare_add_document&lt;/code&gt; holds guards for both the tensor values and the graph; &lt;code&gt;complete_add_document&lt;/code&gt; applies the prepared connections on the writer thread. Prepared references are checked again because nodes may have changed between the two phases. Small graphs use the direct write-thread path so that the first nodes are connected as they are added.&lt;/p&gt;
&lt;h3 id=&quot;removal&quot;&gt;Removal&lt;/h3&gt;
&lt;p&gt;Removing node 5 would affect more than its own arrays: nodes 1 and 4 link to it at level 0, node 1 links to it at level 1, and it is the entry point. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp#L866&quot;&gt;remove_node&lt;/a&gt; visits each level, removes reverse links, and calls &lt;code&gt;mutual_reconnect&lt;/code&gt; to add connections among the former neighbors where possible. It also chooses a new entry point when necessary.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;mutual_reconnect&lt;/code&gt; considers pairs among those neighbors in distance order and respects link limits. It usually caps the number of new connections per node, with an exception for isolated nodes.&lt;/p&gt;
&lt;p&gt;The writer then invalidates the node&#39;s levels reference and retires its arrays. A concurrent query may still arrive at node 5 through a link it read earlier. It checks for invalid references before continuing, while its guard keeps already-acquired storage alive until it finishes.&lt;/p&gt;
</description>
      </item>
      <item>
          <title>Vespa: Thread Safety in the Storage Engine</title>
          <pubDate>Sun, 20 Sep 2026 00:00:00 +0000</pubDate>
          <author>inhzus</author>
          <link>https://zunish.io/posts/2026-09-20-vespa-storage-engine-thread-safety/</link>
          <guid>https://zunish.io/posts/2026-09-20-vespa-storage-engine-thread-safety/</guid>
          <description xml:base="https://zunish.io/posts/2026-09-20-vespa-storage-engine-thread-safety/">&lt;p&gt;&lt;em&gt;Note: This post was refined with AI assistance for clarity and structure.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A query has found a posting list and is walking through it. Meanwhile, a writer replaces some of its nodes. The query already holds references into the old tree, so publishing a new root is only half the job: the old nodes must remain alive until that query finishes.&lt;/p&gt;
&lt;p&gt;The earlier posts described the &lt;a href=&quot;https://zunish.io/posts/2024-12-04-vespa-index-impl/&quot;&gt;index structures&lt;/a&gt; and &lt;a href=&quot;https://zunish.io/posts/2024-12-05-vespa-match-impl/&quot;&gt;matching code&lt;/a&gt;. The question here is how proton, Vespa&#39;s searchnode, lets a reader finish while those structures change underneath it. Source links refer to revision &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/tree/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2&quot;&gt;39bf68f4&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;overview&quot;&gt;Publishing changes and retaining old data&lt;/h2&gt;
&lt;p&gt;Vespa sequences writes to many mutable structures so that each has one writer at a time. Readers continue using published references while that writer prepares changes. There are two separate obligations: publish data so readers can safely access it, and delay reclamation until nobody needs the old storage. Atomic loads and stores, frozen B-tree nodes, and locks handle the first; generation guards handle the second.&lt;/p&gt;
&lt;p&gt;A guard keeps old memory alive. It does not give the query a fixed snapshot across fields or related documents: the query can observe changes published at different times. The &lt;a rel=&quot;external&quot; href=&quot;https://docs.vespa.ai/en/content/consistency.html#read-consistency&quot;&gt;consistency documentation&lt;/a&gt; explicitly allows partial changes to be visible while a write is in progress.&lt;/p&gt;
&lt;p&gt;The same lifetime question returns during a disk-index replacement, where a query holds an entire collection of indexes. Start with a smaller object: one array that a reader is still using.&lt;/p&gt;
&lt;h2 id=&quot;generationhandler&quot;&gt;Following a reader through an update&lt;/h2&gt;
&lt;p&gt;Suppose a reader holds generation 10 and has a reference to array A. The writer allocates array B, publishes its reference, and retires A at generation 10. It can then advance to generation 11. Array A stays on hold until the reader releases its guard and the reclamation boundary advances past 10.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-thread-safety-in-the-storage-engine/generation-lifetime.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-thread-safety-in-the-storage-engine/generation-lifetime.svg&quot; alt=&quot;Timeline showing a reader holding generation 10 while the writer publishes array B and retires array A. A becomes reclaimable only after the guard is released and the oldest-used generation advances past 10.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;A slow reader delays this reclamation. During heavy updates, the writer may retire many more allocations before that reader finishes, increasing on-hold memory.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/vespalib/src/vespa/vespalib/util/generationhandler.cpp&quot;&gt;GenerationHandler&lt;/a&gt; supplies the information needed to decide when A can be freed. It has one writer and tracks the generations held by multiple readers.&lt;/p&gt;
&lt;p&gt;Its main state consists of a current generation number, a linked list of &lt;code&gt;GenerationHold&lt;/code&gt; entries, and a free list for entries that can be reused. &lt;code&gt;_last&lt;/code&gt; identifies the generation acquired by new readers; &lt;code&gt;_first&lt;/code&gt; identifies the oldest retained entry.&lt;/p&gt;
&lt;h3 id=&quot;acquiring-a-guard&quot;&gt;Acquiring a guard&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;takeGuard()&lt;/code&gt; can be simplified to:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;GenerationGuard guard&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;_last&lt;/span&gt;&lt;span&gt;.&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;load&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;std&lt;/span&gt;&lt;span&gt;::memory_order_acquire));&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;while&lt;/span&gt;&lt;span&gt; (&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;!&lt;/span&gt;&lt;span&gt;guard.&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;valid&lt;/span&gt;&lt;span&gt;()) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    guard&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; GenerationGuard&lt;/span&gt;&lt;span&gt;(_last.&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;load&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;std&lt;/span&gt;&lt;span&gt;::memory_order_acquire));&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;}&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;return&lt;/span&gt;&lt;span&gt; guard;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The constructor tries to acquire the &lt;code&gt;GenerationHold&lt;/code&gt;. If that entry was invalidated concurrently, acquisition fails and the reader retries. A successful guard releases its reference when destroyed.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/vespalib/src/vespa/vespalib/util/generation_hold.cpp&quot;&gt;GenerationHold&lt;/a&gt; packs the reader count and an invalid flag into one atomic integer. Each reader adds 2, leaving the lowest bit for the flag. &lt;code&gt;setInvalid()&lt;/code&gt; succeeds only when it can change the value from 0 to 1, so an entry with an active reader cannot be invalidated through that path.&lt;/p&gt;
&lt;p&gt;The handler retains the hold entries for reuse, so a reader attempting acquisition can safely encounter an entry that has left the active list.&lt;/p&gt;
&lt;h3 id=&quot;advancing-the-generation&quot;&gt;Advancing the generation&lt;/h3&gt;
&lt;p&gt;The writer calls &lt;code&gt;incGeneration()&lt;/code&gt; after the surrounding structure has performed its publication work.&lt;/p&gt;
&lt;p&gt;If the newest hold has no readers, the handler can reuse it with the next generation number. Otherwise, it allocates or reuses another hold and publishes it through &lt;code&gt;_last&lt;/code&gt; with release ordering.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;update_oldest_used_generation()&lt;/code&gt; walks from the oldest entry until it reaches one still in use, or the current entry. Stores use this oldest-used generation to decide which retired allocations can be reclaimed.&lt;/p&gt;
&lt;h2 id=&quot;datastore-and-b-trees&quot;&gt;DataStore and B-trees&lt;/h2&gt;
&lt;p&gt;The handler tracks readers; the data store tracks the allocations they may still need. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/vespalib/src/vespa/vespalib/datastore/datastorebase.h&quot;&gt;DataStoreBase&lt;/a&gt; records retired elements and buffers on hold lists and assigns them a generation. In our example, A belongs to generation 10, so the store waits for the oldest reader generation to advance past 10 before reclaiming it.&lt;/p&gt;
&lt;p&gt;Compaction follows the same rule. Moving live data to another buffer does not immediately make the old buffer reusable: a reader may already have resolved an old reference into it.&lt;/p&gt;
&lt;h3 id=&quot;frozen-b-tree-nodes&quot;&gt;Frozen B-tree nodes&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/vespalib/src/vespa/vespalib/btree/btreenodeallocator.h&quot;&gt;BTreeNodeAllocator&lt;/a&gt; applies this to tree nodes. It supports freezing nodes; when the writer later changes a frozen node, it creates a writable copy. Unchanged subtrees can remain shared.&lt;/p&gt;
&lt;p&gt;For the query walking our posting list, the old root still leads to usable nodes. Replaced nodes go on hold, just as array A did, until the reader no longer needs them.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-thread-safety-in-the-storage-engine/frozen-btree.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-thread-safety-in-the-storage-engine/frozen-btree.svg&quot; alt=&quot;An existing reader retains an old frozen B-tree root and leaf. A newly published root points to a copied, updated leaf; both roots share an unchanged frozen subtree.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The memory index puts these steps together in &lt;code&gt;FieldIndex::commit()&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;freeze&lt;/span&gt;&lt;span&gt;();&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;assign_generation&lt;/span&gt;&lt;span&gt;();&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;incGeneration&lt;/span&gt;&lt;span&gt;();&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;reclaim_memory&lt;/span&gt;&lt;span&gt;();&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This excerpt omits the remover flush. Attributes arrange publication differently, so their commit path needs a separate look.&lt;/p&gt;
&lt;h2 id=&quot;threading-at-the-proton-level&quot;&gt;Threading at the proton level&lt;/h2&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcore/proton/server/executorthreadingservice.h&quot;&gt;ExecutorThreadingService&lt;/a&gt; assigns work within each document database. The master thread coordinates operations, while field writers can update different fields concurrently:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Executor&lt;/th&gt;&lt;th&gt;Work&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Master&lt;/td&gt;&lt;td&gt;Sequence document-database operations and coordinate state changes&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Index&lt;/td&gt;&lt;td&gt;Handle index work and dispatch into the memory-index pipeline&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Summary&lt;/td&gt;&lt;td&gt;Handle document-store work&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Field writer&lt;/td&gt;&lt;td&gt;Sequence per-field mutations&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Shared&lt;/td&gt;&lt;td&gt;Run shared tasks, including eligible preparation work&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Flush tasks have separate scheduling and call back into these services to coordinate with writes.&lt;/p&gt;
&lt;h2 id=&quot;attributes&quot;&gt;Attributes&lt;/h2&gt;
&lt;h3 id=&quot;write-sequencing&quot;&gt;Write sequencing&lt;/h3&gt;
&lt;p&gt;Proton&#39;s &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcore/proton/attribute/attribute_writer.cpp&quot;&gt;AttributeWriter&lt;/a&gt; groups attribute work into write contexts with executor ids. Work for a given context is sent through a sequenced executor, so its mutations are ordered. Other contexts can execute in parallel.&lt;/p&gt;
&lt;p&gt;Each attribute therefore has a single mutation sequence without needing a mutex around every value access.&lt;/p&gt;
&lt;h3 id=&quot;commit-and-publication&quot;&gt;Commit and publication&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/attribute/attributevector.cpp#L173&quot;&gt;AttributeVector::commit&lt;/a&gt; invokes the concrete attribute&#39;s &lt;code&gt;onCommit()&lt;/code&gt;, updates the committed document-id limit, and updates statistics. Its serial-number overload also records the last sync token.&lt;/p&gt;
&lt;p&gt;Generation advancement has its own method, &lt;code&gt;incGeneration()&lt;/code&gt;: it calls &lt;code&gt;before_inc_generation&lt;/code&gt;, advances the handler, and reclaims unused memory. The base &lt;code&gt;commit()&lt;/code&gt; has no unconditional call to it. Each concrete attribute arranges publication and generation advancement to suit its storage layout.&lt;/p&gt;
&lt;p&gt;The reader&#39;s access follows that storage layout: an atomic value load, an acquired reference to a replacement array, or a frozen tree root. This is why the base &lt;code&gt;commit()&lt;/code&gt; alone cannot explain how every attribute becomes readable.&lt;/p&gt;
&lt;h3 id=&quot;attributereadguard&quot;&gt;AttributeReadGuard&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/attribute/attributevector.cpp#L668&quot;&gt;makeReadGuard&lt;/a&gt; constructs a guard containing a &lt;code&gt;GenerationGuard&lt;/code&gt; and, optionally, a shared lock on the enum store:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;std&lt;/span&gt;&lt;span&gt;::unique_ptr&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span&gt;AttributeReadGuard&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;AttributeVector&lt;/span&gt;&lt;span&gt;::&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;makeReadGuard&lt;/span&gt;&lt;span&gt;(&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;bool&lt;/span&gt;&lt;span&gt; stableEnumGuard)&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; const&lt;/span&gt;&lt;span&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;    return&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; std&lt;/span&gt;&lt;span&gt;::&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;make_unique&lt;/span&gt;&lt;span&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;ReadGuard&lt;/span&gt;&lt;span&gt;&amp;gt;(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #005CC5;&quot;&gt;        this&lt;/span&gt;&lt;span&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;        _genHandler.&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;takeGuard&lt;/span&gt;&lt;span&gt;(),&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;        stableEnumGuard&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; ? &amp;amp;&lt;/span&gt;&lt;span&gt;_enumLock&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; :&lt;/span&gt;&lt;span style=&quot;color: #005CC5;&quot;&gt; nullptr&lt;/span&gt;&lt;span&gt;);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Stable enum access adds a requirement beyond retaining storage: enum-handle mappings must remain stable too. The shared lock protects those mappings against operations requiring the corresponding exclusive lock. Many ordinary value and posting-list reads avoid this reader/writer lock.&lt;/p&gt;
&lt;h3 id=&quot;imported-attributes&quot;&gt;Imported attributes&lt;/h3&gt;
&lt;p&gt;An imported attribute reads through a reference to another document&#39;s attribute. Keeping only the final value alive is insufficient: the target local id or the reference mapping could be reused in the meantime.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/attribute/imported_attribute_vector_read_guard.h&quot;&gt;ImportedAttributeVectorReadGuard&lt;/a&gt; holds three guards: one for the target attribute, one for the target document meta store, and one for the reference attribute. These retain the objects and mappings needed to follow the reference.&lt;/p&gt;
&lt;h3 id=&quot;flushing&quot;&gt;Flushing&lt;/h3&gt;
&lt;p&gt;An attribute flush begins with work on the attribute&#39;s writer executor. The &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcore/proton/attribute/flushableattribute.cpp#L65&quot;&gt;Flusher constructor&lt;/a&gt; commits through the selected serial number and calls &lt;code&gt;initSave()&lt;/code&gt; to create a saver. Sequencing this setup with writes lets the saver capture the state it needs safely.&lt;/p&gt;
&lt;p&gt;The saver then acts as another reader during the separate file-writing task. Depending on the attribute type, it may retain generation-protected storage or copied data. A saver holding a guard can delay reclamation just like the slow query holding array A. For slow-disk saves, the implementation can shorten that delay by serializing to a memory target, releasing the saver, and then writing the target to disk.&lt;/p&gt;
&lt;p&gt;The snapshot directory is first marked invalid and becomes valid only after a successful save. Incomplete snapshots can then be distinguished during recovery.&lt;/p&gt;
&lt;h3 id=&quot;tensor-attributes-and-hnsw&quot;&gt;Tensor attributes and HNSW&lt;/h3&gt;
&lt;p&gt;HNSW has a relatively expensive preparation step: searching the graph for neighbors of a new vector. Vespa can run that step outside the writer thread, while leaving graph mutation on the writer sequence.&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp#L117&quot;&gt;prepared operation&lt;/a&gt; holds a guard for the attribute&#39;s vector storage and another for the graph. Completion checks prepared references before applying connections, since the graph may have changed during preparation.&lt;/p&gt;
&lt;p&gt;Neighbor-list replacement follows the array A/B example directly. Node removal also removes incoming links and attempts to reconnect neighbors before retiring storage. The &lt;a href=&quot;https://zunish.io/posts/2026-09-20-vespa-hnsw-index/&quot;&gt;HNSW implementation post&lt;/a&gt; follows these updates through the graph&#39;s arrays.&lt;/p&gt;
&lt;h2 id=&quot;memory-index&quot;&gt;Memory index&lt;/h2&gt;
&lt;p&gt;Unlike an attribute that may store one numeric value per document, a text index must update a dictionary, posting lists, and ranking features. Vespa handles this per field.&lt;/p&gt;
&lt;p&gt;A &lt;code&gt;FieldIndex&lt;/code&gt; contains a word store, a dictionary B-tree, posting-list storage, and a feature store. These use the generation-managed containers described above.&lt;/p&gt;
&lt;h3 id=&quot;inversion-and-push&quot;&gt;Inversion and push&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/memoryindex/memory_index.h&quot;&gt;MemoryIndex&lt;/a&gt; separates updating into two asynchronous phases:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Invert documents into per-field terms and occurrences on the invert executors.&lt;/li&gt;
&lt;li&gt;Push the accumulated changes into field indexes on the push executors when committing.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The push work is sequenced per field, so two pushes do not concurrently modify the same field index. Different fields can progress independently. A shared completion callback tracks the lifetime of the submitted work.&lt;/p&gt;
&lt;p&gt;Making the terms searchable requires the asynchronous commit step; returning from &lt;code&gt;insertDocument()&lt;/code&gt; alone is insufficient.&lt;/p&gt;
&lt;h3 id=&quot;reader-lifetime&quot;&gt;Reader lifetime&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchlib/src/vespa/searchlib/memoryindex/field_index.cpp#L284&quot;&gt;FieldIndex::make_term_blueprint&lt;/a&gt; acquires a generation guard before obtaining a frozen posting-list iterator:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;auto&lt;/span&gt;&lt;span&gt; guard&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; takeGenerationGuard&lt;/span&gt;&lt;span&gt;();&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;auto&lt;/span&gt;&lt;span&gt; posting_itr&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; findFrozen&lt;/span&gt;&lt;span&gt;(term);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; std&lt;/span&gt;&lt;span&gt;::&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;make_unique&lt;/span&gt;&lt;span&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;MemoryTermBlueprint&lt;/span&gt;&lt;span&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;interleaved_features&lt;/span&gt;&lt;span&gt;&amp;gt;&amp;gt;(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;    std&lt;/span&gt;&lt;span&gt;::&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;move&lt;/span&gt;&lt;span&gt;(guard),&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; std&lt;/span&gt;&lt;span&gt;::&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;move&lt;/span&gt;&lt;span&gt;(posting_itr),&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; getFeatureStore&lt;/span&gt;&lt;span&gt;(),&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;    field, field_id, term, use_bit_vector);&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is where the posting-list reader from the opening gets its protection. The blueprint owns both the frozen iterator and the guard, keeping the old tree&#39;s storage available as the writer publishes new trees.&lt;/p&gt;
&lt;h3 id=&quot;flushing-the-whole-index&quot;&gt;Flushing the whole index&lt;/h3&gt;
&lt;p&gt;A normal commit freezes B-tree nodes but leaves the memory index open for later writes. To flush the whole index, &lt;code&gt;MemoryIndex::freeze()&lt;/code&gt; stops further updates. New writes go to a replacement memory index while the maintainer dumps the frozen one to disk.&lt;/p&gt;
&lt;p&gt;Freezing stops writes, but it does not end queries already using that index. To follow its lifetime through the flush, we need to look at the collection from which queries acquire their indexes.&lt;/p&gt;
&lt;h2 id=&quot;disk-index&quot;&gt;Disk index&lt;/h2&gt;
&lt;p&gt;Flush and fusion create new index directories, such as &lt;code&gt;index.flush.N&lt;/code&gt; and &lt;code&gt;index.fusion.N&lt;/code&gt;. Their posting and dictionary data are written during construction and stay stable during query traversal. The handover happens by replacing the collection of indexes available to searches.&lt;/p&gt;
&lt;p&gt;Management files such as the schema have separate update rules and locks.&lt;/p&gt;
&lt;h3 id=&quot;replacing-the-searchable-collection&quot;&gt;Replacing the searchable collection&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcorespi/index/indexmaintainer.h&quot;&gt;IndexMaintainer&lt;/a&gt; holds a collection of memory and disk indexes in &lt;code&gt;_source_list&lt;/code&gt;. Updating this collection is coordinated by the document database&#39;s master thread.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;replaceSource()&lt;/code&gt; copies the collection, replaces the relevant source, and calls &lt;code&gt;swapInNewIndex()&lt;/code&gt;. Locks protect assignment to the ordinary &lt;code&gt;shared_ptr&lt;/code&gt; member &lt;code&gt;_source_list&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The reader side is short:&lt;/p&gt;
&lt;pre class=&quot;giallo&quot; style=&quot;color: #24292E; background-color: #FFFFFF;&quot; &gt;&lt;code data-lang=&quot;cpp&quot;&gt;&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;std&lt;/span&gt;&lt;span&gt;::&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;shared_ptr&lt;/span&gt;&lt;span&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;searchcorespi&lt;/span&gt;&lt;span&gt;::&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;IndexSearchable&lt;/span&gt;&lt;span&gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt; getSearchable&lt;/span&gt;&lt;span&gt;()&lt;/span&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt; const override&lt;/span&gt;&lt;span&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #6F42C1;&quot;&gt;    LockGuard lock&lt;/span&gt;&lt;span&gt;(_new_search_lock);&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span style=&quot;color: #D73A49;&quot;&gt;    return&lt;/span&gt;&lt;span&gt; _source_list;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;giallo-l&quot;&gt;&lt;span&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After acquiring the pointer, the reader can keep using that collection even if the maintainer installs another one. The lock covers acquisition and replacement, rather than the entire query.&lt;/p&gt;
&lt;p&gt;The retained collection can still contain an active memory index. Queries use that index&#39;s generation guards to protect their reads while it changes.&lt;/p&gt;
&lt;p&gt;In this flush, a disk index replaces the frozen memory index while unchanged sources remain shared. The old query keeps its original collection. Warmup, covered below, can delay the handover to the new one.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://image.zunish.io/posts/vespa-thread-safety-in-the-storage-engine/collection-replacement.svg&quot;&gt;&lt;img src=&quot;https://image.zunish.io/posts/vespa-thread-safety-in-the-storage-engine/collection-replacement.svg&quot; alt=&quot;Before a flush replacement, the current collection contains a frozen memory index, an active memory index, and an existing disk index. Afterwards, an old query retains that collection while new queries acquire a collection containing the disk replacement. Both collections share the active memory index and existing disk index.&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Flush work copies the state it needs, performs disk work separately, and schedules the resulting state change on the master thread. If intervening changes make the prepared state unsuitable, the operation may need to retry with updated state.&lt;/p&gt;
&lt;h3 id=&quot;flush-and-fusion&quot;&gt;Flush and fusion&lt;/h3&gt;
&lt;p&gt;The flush shown above loads the newly written disk index before replacing the frozen memory source. Fusion uses the same handover to replace several disk indexes with one combined index. In both cases, the old collection remains usable by queries that already acquired it.&lt;/p&gt;
&lt;p&gt;Old directories cannot be deleted merely because they disappeared from the newest collection. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcorespi/index/disk_indexes.h&quot;&gt;DiskIndexes&lt;/a&gt; tracks indexes still in use, and cleanup waits until they are no longer needed. &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcorespi/index/diskindexcleaner.cpp&quot;&gt;DiskIndexCleaner&lt;/a&gt; removes &lt;code&gt;serial.dat&lt;/code&gt; and syncs the directory before deleting its remaining contents. A directory without that validity marker is recognized as invalid during cleanup after restart.&lt;/p&gt;
&lt;h3 id=&quot;warmup&quot;&gt;Warmup&lt;/h3&gt;
&lt;p&gt;If configured, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/vespa-engine/vespa/blob/39bf68f4ce9ea144c5f3a2bb2fd22890fd680ec2/searchcore/src/vespa/searchcorespi/index/warmupindexcollection.cpp&quot;&gt;WarmupIndexCollection&lt;/a&gt; temporarily retains both the previous and next collections. Queries are served from the previous collection while observed query terms cause work against the new disk index to be scheduled on a background executor.&lt;/p&gt;
&lt;p&gt;After the configured period, the handover can complete. Only terms observed during warmup have caused background work, so later queries can still encounter cold pages. Caches, lazy loading, and statistics may also require synchronization during disk reads, even though the posting data itself stays unchanged.&lt;/p&gt;
&lt;h3 id=&quot;locks&quot;&gt;Locks&lt;/h3&gt;
&lt;p&gt;The lock annotations in &lt;code&gt;IndexMaintainer&lt;/code&gt; are useful when following flush and fusion:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Lock&lt;/th&gt;&lt;th&gt;Main responsibility&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;_state_lock&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Read or update a coordinated set of maintainer state&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;_index_update_lock&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Index-update state, including generation-change tracking&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;_new_search_lock&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Access to the searchable collection&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;_fusion_lock&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Fusion specification&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;_schemaUpdateLock&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Schema rewrites&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;_remove_lock&lt;/code&gt;&lt;/td&gt;&lt;td&gt;Index-directory removal&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Some variables are protected by more than one lock. The source comment specifies that changing such a variable requires all its associated locks; reading it requires any one of them.&lt;/p&gt;
</description>
      </item>
      <item>
          <title>新鲜软件体验记录</title>
          <pubDate>Thu, 15 Jan 2026 18:00:00 +0800</pubDate>
          <author>inhzus</author>
          <link>https://zunish.io/posts/2026-01-13-apps/</link>
          <guid>https://zunish.io/posts/2026-01-13-apps/</guid>
          <description xml:base="https://zunish.io/posts/2026-01-13-apps/">&lt;p&gt;&lt;a href=&quot;/posts/2026-01-13-apps/&quot;&gt;中文&lt;/a&gt; &lt;a href=&quot;/posts/gen/2026-01-13-apps/&quot;&gt;English&lt;/a&gt;&lt;/p&gt;
&lt;h2 id=&quot;macos-apps&quot;&gt;MacOS Apps&lt;/h2&gt;
&lt;h3 id=&quot;shi-yong-zhong&quot;&gt;使用中&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://brave.com/&quot;&gt;Brave Browser&lt;/a&gt; #browser
&lt;ul&gt;
&lt;li&gt;性能和功能的平衡之选；&lt;/li&gt;
&lt;li&gt;内置广告过滤规则，好用的垂直标签页；&lt;/li&gt;
&lt;li&gt;Web3 相关按钮较多，可关闭；&lt;/li&gt;
&lt;li&gt;注意关闭硬件加速选项，否则在 mbp 上耗电严重；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://segev.sh/dory/&quot;&gt;Dory&lt;/a&gt; #switcher
&lt;ul&gt;
&lt;li&gt;与 &lt;a rel=&quot;external&quot; href=&quot;https://lowtechguys.com/rcmd/&quot;&gt;rcmd&lt;/a&gt; 类似，更清爽；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/ghostty-org/ghostty&quot;&gt;Ghostty&lt;/a&gt; #terminal emulator
&lt;ul&gt;
&lt;li&gt;与 wezterm 无异，简洁易配置；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://herdr.dev/&quot;&gt;Herdr&lt;/a&gt; #terminal multiplexer
&lt;ul&gt;
&lt;li&gt;目前主要用于通过 SSH 连接远程机器，运行和管理 AI coding agents；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://updatest.app/&quot;&gt;Updatest&lt;/a&gt; #updater
&lt;ul&gt;
&lt;li&gt;App 更新器，在其帮助下把很多软件转 homebrew 管理；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://netnewswire.com/&quot;&gt;NetNewsWire&lt;/a&gt; #rss
&lt;ul&gt;
&lt;li&gt;RSS 阅读器，macOS/iOS 跨平台原生，简洁流畅、功能够用；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://sindresorhus.com/velja&quot;&gt;Velja&lt;/a&gt; #browser picker
&lt;ul&gt;
&lt;li&gt;点击 URL 后会根据规则跳转对应浏览器；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/ronitsingh10/FineTune&quot;&gt;FineTune&lt;/a&gt; #audio
&lt;ul&gt;
&lt;li&gt;开源，为每个 app 设置独立音量、音频输出、EQ；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;guan-zhu-zhong&quot;&gt;关注中&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/imputnet/helium&quot;&gt;Helium Browser&lt;/a&gt; #browser
&lt;ul&gt;
&lt;li&gt;Chrome 巨无霸的替代品，隐私优先，但不支持垂直标签页；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/wezterm/wezterm&quot;&gt;wezterm&lt;/a&gt; #terminal emulator
&lt;ul&gt;
&lt;li&gt;正式版很久不更新，新鲜感已过😁；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://max.codes/latest/&quot;&gt;Latest&lt;/a&gt; #updater
&lt;ul&gt;
&lt;li&gt;免费开源，但功能不如付费的 Updatest；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://orionbrowser.com/&quot;&gt;Orion&lt;/a&gt; #browser
&lt;ul&gt;
&lt;li&gt;基于 webkit 的浏览器，可惜目前 bug 太多，更新较慢；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://zed.dev/&quot;&gt;Zed&lt;/a&gt; #editor
&lt;ul&gt;
&lt;li&gt;Rust 实现的编辑器，可扩展性和可自定义选项和 VSC 有差距；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;yi-fang-qi&quot;&gt;已放弃&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://chatwise.app/&quot;&gt;ChatWise&lt;/a&gt; #chatbox
&lt;ul&gt;
&lt;li&gt;主观感受 macOS native UI 的最佳之选；&lt;/li&gt;
&lt;li&gt;ChatGPT 太强了，不得已淘汰 ChatWise；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://cotypist.app/&quot;&gt;Cotypist&lt;/a&gt; #ai
&lt;ul&gt;
&lt;li&gt;在任何窗口下 AI 自动补全；&lt;/li&gt;
&lt;li&gt;效果一般，有点烦人；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://folo.is/&quot;&gt;Folo&lt;/a&gt; #rss
&lt;ul&gt;
&lt;li&gt;UI 卡顿，功能鸡肋，不务正业；&lt;/li&gt;
&lt;li&gt;自从 all in AI，UI 改版后直接放弃；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;cli&quot;&gt;CLI&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://pixi.prefix.dev/&quot;&gt;pixi&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;Linux 共享机器在个人目录下安装 cli 的最佳选项，开箱即用；&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://mise.jdx.dev/&quot;&gt;mise&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;项目级环境管理&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;choose-rust / cut&lt;/li&gt;
&lt;li&gt;fd-find / find&lt;/li&gt;
&lt;li&gt;ripgrep / grep&lt;/li&gt;
&lt;li&gt;xh / httpie / curl&lt;/li&gt;
&lt;li&gt;minio-mc&lt;/li&gt;
&lt;/ul&gt;
</description>
      </item>
    </channel>
</rss>
