ronantakizawa/codereview-bench huggingface dataset:
Repository: vercel/next.js
File: test/e2e/app-dir/errors/app/server-component/recover/page.js (JavaScript)

Code before:
import { Suspense } from 'react'
import { connection } from 'next/server'

export default function Page() {
  return (
    <Suspense>
      <PageImpl />
    </Suspense>
  )
}

let hasThrown = false

async function PageImpl() {
  // Throw only during the runtime
  await connection()

  if (!hasThrown) {
    hasThrown = true
    throw new Error('this is a test')
  }

  return <p id="recover">Recovered</p>
}


Review comment (suggestion):
we should add indirection components around the error. the component stack and ownerstack should reflect these indirections

Code after:
import { Suspense } from 'react'
import { connection } from 'next/server'

export default function Page() {
  return (
    <Suspense>
      <Container>
        <Content />
      </Container>
    </Suspense>
  )
}

function Container({ children }) {
  return <div>{children}</div>
}

async function Content() {
  await connection()

  if (!globalThis.__nextTestRecover) {
    throw new Error('this is a test')
  }

  return <p id="recover">Recovered</p>
}
Repository: vercel/next.js
File: packages/next/src/client/components/segment-cache/lru.ts (TypeScript)

Code before:
      if (next === head) {
        // This was the last entry
        head = null
      } else {
        head = next
        prev.next = next
        next.prev = prev
      }
    } else {
      prev.next = next
      next.prev = prev
    }
  } else {
    // Already deleted
  }
}

function ensureCleanupIsScheduled() {
  if (lruSize <= maxLruSize) {
    return
  }
  scheduleCleanup()
}

export function registerScheduleCleanup(cb: () => void) {
  scheduleCleanup = cb
}

export function cleanup() {
  if (lruSize <= maxLruSize) {
    return
  }

  // Evict entries until we're at 90% capacity. We can assume this won't
  // infinite loop because even if `maxLruSize` were 0, eventually
  // `deleteFromLru` sets `head` to `null` when we run out entries.
  const ninetyPercentMax = maxLruSize * 0.9
  while (lruSize > ninetyPercentMax && head !== null) {
    const tail = head.prev
    // In practice, this is never null, but that isn't encoded in the type
    if (tail !== null) {
      // Delete the entry from the map. In turn, this will remove it from
      // the LRU.
      deleteMapEntry(tail)
    }
  }
}


Review comment (suggestion):
These modules don’t need to be decoupled. You can import the function directly. Maybe rename it to pingPrefetchScheduler  or something.

Code after:
      if (next === head) {
        // This was the last entry
        head = null
      } else {
        head = next
        prev.next = next
        next.prev = prev
      }
    } else {
      prev.next = next
      next.prev = prev
    }
  } else {
    // Already deleted
  }
}

function ensureCleanupIsScheduled() {
  if (lruSize <= maxLruSize) {
    return
  }

  // To schedule cleanup, ping the prefetch scheduler. At the end of its work
  // loop, once there are no queued tasks and no in-progress requests, it will
  // call cleanup().
  pingPrefetchScheduler()
}

export function cleanup() {
  if (lruSize <= maxLruSize) {
    return
  }

  // Evict entries until we're at 90% capacity. We can assume this won't
  // infinite loop because even if `maxLruSize` were 0, eventually
  // `deleteFromLru` sets `head` to `null` when we run out entries.
  const ninetyPercentMax = maxLruSize * 0.9
  while (lruSize > ninetyPercentMax && head !== null) {
    const tail = head.prev
    // In practice, this is never null, but that isn't encoded in the type
    if (tail !== null) {
      // Delete the entry from the map. In turn, this will remove it from
      // the LRU.
      deleteMapEntry(tail)
    }
  }
}
Repository: vercel/next.js
File: crates/next-custom-transforms/src/transforms/debug_instant_stack.rs (Rust)

Code before:
use swc_core::{
    common::{Span, Spanned},
    ecma::{
        ast::*,
        visit::{fold_pass, Fold},
    },
    quote,
};

pub fn debug_instant_stack() -> impl Pass {
    fold_pass(DebugInstantStack {
        instant_export_span: None,
    })
}

struct DebugInstantStack {
    instant_export_span: Option<Span>,
}

/// Given an export specifier, returns `Some((exported_name, local_name))` if
/// the exported name is `unstable_instant`.
fn get_instant_specifier_names(specifier: &ExportSpecifier) -> Option<(&Ident, &Ident)> {
    match specifier {
        // `export { orig as unstable_instant }`
        ExportSpecifier::Named(ExportNamedSpecifier {
            exported: Some(ModuleExportName::Ident(exported)),
            orig: ModuleExportName::Ident(orig),
            ..
        }) if exported.sym == "unstable_instant" => Some((exported, orig)),
        // `export { unstable_instant }`
        ExportSpecifier::Named(ExportNamedSpecifier {
            exported: None,
            orig: ModuleExportName::Ident(orig),
            ..
        }) if orig.sym == "unstable_instant" => Some((orig, orig)),
        _ => None,
    }
}


Review comment (suggestion):
We probably want to pass `next_config.page_extensions()` from `crates/next-core/src/next_server/transforms.rs` into this transform and use it here.

Code after:
use once_cell::sync::Lazy;
use regex::Regex;
use swc_core::{
    common::{Span, Spanned},
    ecma::{
        ast::*,
        visit::{fold_pass, Fold},
    },
    quote,
};

/// Only apply to page/layout segment files.
static PAGE_OR_LAYOUT_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"[\\/](page|layout|default)\.(ts|js)x?$").unwrap());

pub fn debug_instant_stack(filepath: String) -> impl Pass {
    fold_pass(DebugInstantStack {
        filepath,
        instant_export_span: None,
    })
}

struct DebugInstantStack {
    filepath: String,
    instant_export_span: Option<Span>,
}

/// Given an export specifier, returns `Some((exported_name, local_name))` if
/// the exported name is `unstable_instant`.
fn get_instant_specifier_names(specifier: &ExportSpecifier) -> Option<(&Ident, &Ident)> {
    match specifier {
        // `export { orig as unstable_instant }`
        ExportSpecifier::Named(ExportNamedSpecifier {
            exported: Some(ModuleExportName::Ident(exported)),
            orig: ModuleExportName::Ident(orig),
            ..
        }) if exported.sym == "unstable_instant" => Some((exported, orig)),
        // `export { unstable_instant }`
        ExportSpecifier::Named(ExportNamedSpecifier {
Repository: vercel/next.js
File: turbopack/crates/turbopack-core/src/source_map/utils.rs (Rust)

Code before:
use std::{borrow::Cow, collections::HashSet, iter};

use anyhow::{Context, Result};
use const_format::concatcp;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, ValueToString};
use turbo_tasks_fs::{
    DiskFileSystem, FileContent, FileSystemPath, rope::Rope, util::uri_from_path_buf,
};
use url::Url;

use crate::SOURCE_URL_PROTOCOL;

fn should_ignore_source(source: &str) -> bool {
    source.starts_with(concatcp!(SOURCE_URL_PROTOCOL, "///[next]"))
        || source.starts_with(concatcp!(SOURCE_URL_PROTOCOL, "///[turbopack]"))
        || source.contains("/node_modules/")
        || source.ends_with("__nextjs-internal-proxy.cjs")
        || source.ends_with("__nextjs-internal-proxy.mjs")
}

pub fn add_default_ignore_list(map: &mut swc_sourcemap::SourceMap) {
    let mut ignored_ids = HashSet::new();

    for (source_id, source) in map.sources().enumerate() {
        if should_ignore_source(source) {
            ignored_ids.insert(source_id);
        }
    }

    for ignored_id in ignored_ids {
        map.add_to_ignore_list(ignored_id as _);
    }
}

#[derive(Serialize, Deserialize)]
struct SourceMapSectionOffsetJson {
    line: u32,
    offset: u32,
}

#[derive(Serialize, Deserialize)]
struct SourceMapSectionItemJson {
    offset: SourceMapSectionOffsetJson,

Review comment (suggestion):
I suspect all of these cases except `/node_modules/` are now obsolete. I'll test this out in a follow-up. 

Code after:
use std::{borrow::Cow, collections::HashSet, iter};

use anyhow::{Context, Result};
use const_format::concatcp;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, ValueToString};
use turbo_tasks_fs::{
    DiskFileSystem, FileContent, FileSystemPath, rope::Rope, util::uri_from_path_buf,
};
use url::Url;

use crate::SOURCE_URL_PROTOCOL;

pub fn add_default_ignore_list(map: &mut swc_sourcemap::SourceMap) {
    let mut ignored_ids = HashSet::new();

    for (source_id, source) in map.sources().enumerate() {
        if source.starts_with(concatcp!(SOURCE_URL_PROTOCOL, "///[next]"))
            || source.starts_with(concatcp!(SOURCE_URL_PROTOCOL, "///[turbopack]"))
            || source.contains("/node_modules/")
            || source.ends_with("__nextjs-internal-proxy.cjs")
            || source.ends_with("__nextjs-internal-proxy.mjs")
        {
            ignored_ids.insert(source_id);
        }
    }

    for ignored_id in ignored_ids {
        map.add_to_ignore_list(ignored_id as _);
    }
}

#[derive(Serialize, Deserialize)]
struct SourceMapSectionOffsetJson {
    line: u32,
    offset: u32,
}

#[derive(Serialize, Deserialize)]
struct SourceMapSectionItemJson {
    offset: SourceMapSectionOffsetJson,
    map: SourceMapJson,
}
Repository: vercel/next.js
File: packages/next/src/shared/lib/get-img-props.ts (TypeScript)

Code before:
  sizes?: string
}

type GenImgAttrsResult = {
  src: string
  srcSet: string | undefined
  sizes: string | undefined
}

function generateImgAttrs({
  config,
  src,
  unoptimized,
  width,
  quality,
  sizes,
  loader,
}: GenImgAttrsData): GenImgAttrsResult {
  if (unoptimized) {
    if (src.startsWith('/') && !src.startsWith('//')) {
      let deploymentId = getDeploymentId()
      const srcUrl = new URL(src, 'http://n')
      const srcDpl = srcUrl.searchParams.get('dpl')
      if (!srcDpl && deploymentId) {
        // src is missing the dpl parameter, but we have a deploymentId, so add it to the src URL
        srcUrl.searchParams.append('dpl', deploymentId)
        src = srcUrl.href.slice('http://n'.length)
      }
    }
    return { src, srcSet: undefined, sizes: undefined }
  }

  const { widths, kind } = getWidths(config, width, sizes)
  const last = widths.length - 1

  return {
    sizes: !sizes && kind === 'w' ? '100vw' : sizes,
    srcSet: widths
      .map(
        (w, i) =>
          `${loader({ config, src, quality, width: w })} ${
            kind === 'w' ? w : i + 1
          }${kind}`
      )
      .join(', '),

    // It's intended to keep `src` the last attribute because React updates
    // attributes in order. If we keep `src` the first one, Safari will
    // immediately start to fetch `src`, before `sizes` and `srcSet` are even
    // updated by React. That causes multiple unnecessary requests if `srcSet`
    // and `sizes` are defined.

Review comment (suggestion):
```suggestion
        srcUrl.searchParams.set('dpl', deploymentId)
```

Let's use set() instead since we don't want multiple `dpl` params

Code after:
  sizes?: string
}

type GenImgAttrsResult = {
  src: string
  srcSet: string | undefined
  sizes: string | undefined
}

function generateImgAttrs({
  config,
  src,
  unoptimized,
  width,
  quality,
  sizes,
  loader,
}: GenImgAttrsData): GenImgAttrsResult {
  if (unoptimized) {
    if (src.startsWith('/') && !src.startsWith('//')) {
      let deploymentId = getDeploymentId()
      if (deploymentId) {
        const srcUrl = new URL(src, 'http://n')
        const srcDpl = srcUrl.searchParams.get('dpl')
        if (!srcDpl) {
          // src is missing the dpl parameter, but we have a deploymentId, so add it to the src URL
          srcUrl.searchParams.set('dpl', deploymentId)
          src = srcUrl.href.slice('http://n'.length)
        }
      }
    }
    return { src, srcSet: undefined, sizes: undefined }
  }

  const { widths, kind } = getWidths(config, width, sizes)
  const last = widths.length - 1

  return {
    sizes: !sizes && kind === 'w' ? '100vw' : sizes,
    srcSet: widths
      .map(
        (w, i) =>
          `${loader({ config, src, quality, width: w })} ${
            kind === 'w' ? w : i + 1
          }${kind}`
      )
      .join(', '),

    // It's intended to keep `src` the last attribute because React updates
    // attributes in order. If we keep `src` the first one, Safari will
    // immediately start to fetch `src`, before `sizes` and `srcSet` are even
Repository: vercel/next.js
File: test/development/app-dir/server-hmr/server-hmr.test.ts (TypeScript)

Code before:
  })

  describe('route handler hmr', () => {
    itTurbopackDev(
      'does not use server hmr. reflects route handler changes on fetch/refresh',
      async () => {
        const initial = await next
          .fetch('/api/hello')
          .then((res) => res.ok && res.text())
        expect(initial).toBe('version: 0')

        await next.patchFile('app/api/hello/route.ts', (content) =>
          content.replace('version: 0', 'version: 1')
        )

        await retry(async () => {
          const updated = await next
            .fetch('/api/hello')
            .then((res) => res.ok && res.text())
          expect(updated).toBe('version: 1')
        })
      }
    )
  })
})


Review comment (suggestion):
Shouldn't the test just always run,regardless of bundler? And then drop the `does not use server hmr. ` part

Code after:
    )
  })

  describe('route handler hmr', () => {
    function getText(res: Response) {
      return res.ok
        ? res.text()
        : Promise.reject(
            new Error('Failed to fetch route handler: ' + res.status)
          )
    }

    it('reflects route handler changes on fetch/refresh', async () => {
      const initial = await next.fetch('/api/hello').then(getText)
      expect(initial).toBe('version: 0')

      await next.patchFile('app/api/hello/route.ts', (content) =>
        content.replace('version: 0', 'version: 1')
      )

      await retry(async () => {
        const updated = await next.fetch('/api/hello').then(getText)
        expect(updated).toBe('version: 1')
      })
    })
  })
})
Repository: vespa-engine/vespa
File: .github/scripts/publish-unpublished-rpms-to-archive.sh (Shell)

Code before:
#!/usr/bin/env bash
#
# Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#

set -o errexit
set -o nounset
set -o pipefail

if [[ -n "${RUNNER_DEBUG:-}" ]]; then
    set -o xtrace
fi

if (( $# < 2 )); then
    echo "Usage: $0 <RPM architecture> <OS version>"
    exit 1
fi

RPMARCH=$1
OSVERSION=$2
ALLOWED_ARCHS=("x86_64" "aarch64")
ALLOWED_VERSIONS=("8" "9")

if [[ " ${ALLOWED_ARCHS[*]} " != " $RPMARCH " ]]; then
  echo "Architecture $RPMARCH not in allowed archs: ${ALLOWED_ARCHS[*]}"
  exit 1
fi

if [[ " ${ALLOWED_VERSIONS[*]} " != " $OSVERSION " ]]; then
  echo "OS version $OSVERSION not in allowed versions: ${ALLOWED_VERSIONS[*]}"
  exit 1
fi


MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
readonly MYDIR

# Copr repo
dnf config-manager --add-repo "https://copr.fedorainfracloud.org/coprs/g/vespa/vespa/repo/epel-${OSVERSION}/group_vespa-vespa-epel-${OSVERSION}.repo"
sed -i "s,\$basearch,$RPMARCH,g" "/etc/yum.repos.d/group_vespa-vespa-epel-${OSVERSION}.repo"

# Cloudsmith repo
rpm --import 'https://dl.cloudsmith.io/public/vespa/open-source-rpms/gpg.0F3DA3C70D35DA7B.key'
curl -1sLf "https://dl.cloudsmith.io/public/vespa/open-source-rpms/config.rpm.txt?distro=el&codename=${OSVERSION}" > /tmp/vespa-open-source-rpms.repo
dnf config-manager --add-repo '/tmp/vespa-open-source-rpms.repo'
rm -f /tmp/vespa-open-source-rpms.repo

COPR_PACKAGES=$(mktemp)
DLDIR=$(mktemp -d)

Review comment (suggestion):
```suggestion
if [[ ! " ${ALLOWED_ARCHS[*]} " =~ " $RPMARCH " ]]; then
```

Code after:
#!/usr/bin/env bash
#
# Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#

set -o errexit
set -o nounset
set -o pipefail

if [[ -n "${RUNNER_DEBUG:-}" ]]; then
    set -o xtrace
fi

if (( $# < 2 )); then
    echo "Usage: $0 <RPM architecture> <OS version>"
    exit 1
fi

RPMARCH=$1
OSVERSION=$2
ALLOWED_ARCHS=("x86_64" "aarch64")
ALLOWED_VERSIONS=("8" "9")

# shellcheck disable=SC2076
if [[ ! " ${ALLOWED_ARCHS[*]} " =~ " ${RPMARCH} " ]]; then
  echo "Architecture $RPMARCH not in allowed archs: ${ALLOWED_ARCHS[*]}"
  exit 1
fi

# shellcheck disable=SC2076
if [[ ! " ${ALLOWED_VERSIONS[*]} " =~ " ${OSVERSION} " ]]; then
  echo "OS version $OSVERSION not in allowed versions: ${ALLOWED_VERSIONS[*]}"
  exit 1
fi


MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
readonly MYDIR

# Copr repo
dnf config-manager --add-repo "https://copr.fedorainfracloud.org/coprs/g/vespa/vespa/repo/epel-${OSVERSION}/group_vespa-vespa-epel-${OSVERSION}.repo"
sed -i "s,\$basearch,$RPMARCH,g" "/etc/yum.repos.d/group_vespa-vespa-epel-${OSVERSION}.repo"

# Cloudsmith repo
rpm --import 'https://dl.cloudsmith.io/public/vespa/open-source-rpms/gpg.0F3DA3C70D35DA7B.key'
curl -1sLf "https://dl.cloudsmith.io/public/vespa/open-source-rpms/config.rpm.txt?distro=el&codename=${OSVERSION}" > /tmp/vespa-open-source-rpms.repo
dnf config-manager --add-repo '/tmp/vespa-open-source-rpms.repo'
rm -f /tmp/vespa-open-source-rpms.repo
Repository: vespa-engine/vespa
File: .github/scripts/publish-unpublished-rpms-to-archive.sh (Shell)

Code before:
#

set -o errexit
set -o nounset
set -o pipefail

if [[ -n "${RUNNER_DEBUG:-}" ]]; then
    set -o xtrace
fi

if (( $# < 2 )); then
    echo "Usage: $0 <RPM architecture> <OS version>"
    exit 1
fi

RPMARCH=$1
OSVERSION=$2
ALLOWED_ARCHS=("x86_64" "aarch64")
ALLOWED_VERSIONS=("8" "9")

if [[ " ${ALLOWED_ARCHS[*]} " != " $RPMARCH " ]]; then
  echo "Architecture $RPMARCH not in allowed archs: ${ALLOWED_ARCHS[*]}"
  exit 1
fi

if [[ " ${ALLOWED_VERSIONS[*]} " != " $OSVERSION " ]]; then
  echo "OS version $OSVERSION not in allowed versions: ${ALLOWED_VERSIONS[*]}"
  exit 1
fi


MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
readonly MYDIR

# Copr repo
dnf config-manager --add-repo "https://copr.fedorainfracloud.org/coprs/g/vespa/vespa/repo/epel-${OSVERSION}/group_vespa-vespa-epel-${OSVERSION}.repo"
sed -i "s,\$basearch,$RPMARCH,g" "/etc/yum.repos.d/group_vespa-vespa-epel-${OSVERSION}.repo"

# Cloudsmith repo
rpm --import 'https://dl.cloudsmith.io/public/vespa/open-source-rpms/gpg.0F3DA3C70D35DA7B.key'
curl -1sLf "https://dl.cloudsmith.io/public/vespa/open-source-rpms/config.rpm.txt?distro=el&codename=${OSVERSION}" > /tmp/vespa-open-source-rpms.repo
dnf config-manager --add-repo '/tmp/vespa-open-source-rpms.repo'
rm -f /tmp/vespa-open-source-rpms.repo

COPR_PACKAGES=$(mktemp)
DLDIR=$(mktemp -d)
readonly COPR_PACKAGES DLDIR

# shellcheck disable=SC2064
trap "rm -rf \"${COPR_PACKAGES}\" \"$DLDIR\"" EXIT


Review comment (suggestion):
```suggestion
if [[ ! " ${ALLOWED_VERSIONS[*]} " =~ " $OSVERSION " ]]; then
```

Code after:
#

set -o errexit
set -o nounset
set -o pipefail

if [[ -n "${RUNNER_DEBUG:-}" ]]; then
    set -o xtrace
fi

if (( $# < 2 )); then
    echo "Usage: $0 <RPM architecture> <OS version>"
    exit 1
fi

RPMARCH=$1
OSVERSION=$2
ALLOWED_ARCHS=("x86_64" "aarch64")
ALLOWED_VERSIONS=("8" "9")

# shellcheck disable=SC2076
if [[ ! " ${ALLOWED_ARCHS[*]} " =~ " ${RPMARCH} " ]]; then
  echo "Architecture $RPMARCH not in allowed archs: ${ALLOWED_ARCHS[*]}"
  exit 1
fi

# shellcheck disable=SC2076
if [[ ! " ${ALLOWED_VERSIONS[*]} " =~ " ${OSVERSION} " ]]; then
  echo "OS version $OSVERSION not in allowed versions: ${ALLOWED_VERSIONS[*]}"
  exit 1
fi


MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
readonly MYDIR

# Copr repo
dnf config-manager --add-repo "https://copr.fedorainfracloud.org/coprs/g/vespa/vespa/repo/epel-${OSVERSION}/group_vespa-vespa-epel-${OSVERSION}.repo"
sed -i "s,\$basearch,$RPMARCH,g" "/etc/yum.repos.d/group_vespa-vespa-epel-${OSVERSION}.repo"

# Cloudsmith repo
rpm --import 'https://dl.cloudsmith.io/public/vespa/open-source-rpms/gpg.0F3DA3C70D35DA7B.key'
curl -1sLf "https://dl.cloudsmith.io/public/vespa/open-source-rpms/config.rpm.txt?distro=el&codename=${OSVERSION}" > /tmp/vespa-open-source-rpms.repo
dnf config-manager --add-repo '/tmp/vespa-open-source-rpms.repo'
rm -f /tmp/vespa-open-source-rpms.repo

COPR_PACKAGES=$(mktemp)
DLDIR=$(mktemp -d)
readonly COPR_PACKAGES DLDIR

# shellcheck disable=SC2064
Repository: vespa-engine/vespa
File: searchlib/src/vespa/searchlib/tensor/hnsw_index.cpp (C++)

Code before:
{
    LinkArray new_links;
    auto old_links = _graph.get_link_array(remove_from, level);
    new_links.reserve(old_links.size());
    for (uint32_t id : old_links) {
        if (id != remove_id) new_links.push_back(id);
    }
    _graph.set_link_array(remove_from, level, new_links);
}

namespace {

double
calc_distance_helper(const BoundDistanceFunction &df, vespalib::eval::TypedCells rhs)
{
    if (rhs.non_existing_attribute_value()) [[unlikely]] {
        /*
         * We are in a read thread and the write thread has removed the
         * tensor.
         */
        return std::numeric_limits<double>::max();
    }
    return df.calc(rhs);
}

void prefetch_docid(const DocVectorAccess& vectors, std::uint32_t docid)
{
    vectors.prefetch_docid(docid);
}

void prefetch_vector(const DocVectorAccess& vectors, std::uint32_t docid)
{
    vectors.prefetch_vector(docid);
}

}

template <HnswIndexType type>
double
HnswIndex<type>::calc_distance(const BoundDistanceFunction &df, uint32_t rhs_nodeid) const
{
    auto rhs = get_vector(rhs_nodeid);
    return calc_distance_helper(df, rhs);
}

template <HnswIndexType type>
double
HnswIndex<type>::calc_distance(const BoundDistanceFunction &df, uint32_t rhs_docid, uint32_t rhs_subspace) const
{
    auto rhs = get_vector(rhs_docid, rhs_subspace);
    return calc_distance_helper(df, rhs);

Review comment (suggestion):
We generally do not use `std::` prefixes with fundamental numeric types; prefer `uint32_t` instead.

Code after:
{
    LinkArray new_links;
    auto old_links = _graph.get_link_array(remove_from, level);
    new_links.reserve(old_links.size());
    for (uint32_t id : old_links) {
        if (id != remove_id) new_links.push_back(id);
    }
    _graph.set_link_array(remove_from, level, new_links);
}

namespace {

double
calc_distance_helper(const BoundDistanceFunction &df, vespalib::eval::TypedCells rhs)
{
    if (rhs.non_existing_attribute_value()) [[unlikely]] {
        /*
         * We are in a read thread and the write thread has removed the
         * tensor.
         */
        return std::numeric_limits<double>::max();
    }
    return df.calc(rhs);
}

void prefetch_docid(const DocVectorAccess& vectors, uint32_t docid)
{
    vectors.prefetch_docid(docid);
}

void prefetch_vector(const DocVectorAccess& vectors, uint32_t docid)
{
    vectors.prefetch_vector(docid);
}

}

template <HnswIndexType type>
double
HnswIndex<type>::calc_distance(const BoundDistanceFunction &df, uint32_t rhs_nodeid) const
{
    auto rhs = get_vector(rhs_nodeid);
    return calc_distance_helper(df, rhs);
}

template <HnswIndexType type>
double
HnswIndex<type>::calc_distance(const BoundDistanceFunction &df, uint32_t rhs_docid, uint32_t rhs_subspace) const
{
    auto rhs = get_vector(rhs_docid, rhs_subspace);
    return calc_distance_helper(df, rhs);