SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2607.19957 · 2026

HIJACKKV: New Threat in Position-Independent KV Cache Reuse

Huan Zhang, Yichi Zhang, Yuchen Yang, Zhiqi Wang

arXiv · PDF · Open in the Atlas

Code that ran

9 of 19 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (2 of them constructed an object rather than computing a result; 3 honoured the contract we drafted, 0 violated it and 2 have no contract verdict; 4 failures of our instrument; 10 no recorded run), measured 2026-11-23; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2607.19957.json · badge: /api/ran/2607.19957.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
YichiCS/KV-Cache-Hijack community
Papers with Code archive
9 ran · 10 no recorded run
FunctionStatusWhere it lives
_MutableFullCache Ran
ran on a synthesized input · constructed an object; no result was computed
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("27f464382c95bbe9")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, _MutableFullCache: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from transformers import Cache

torch.manual_seed(0)

# Create a minimal layer class that has keys and values attributes
class MinimalLayer:
    def __init__(self, batch_size=2, key_dim=4, value_dim=3):
        self.keys = torch.randn(batch_size, key_dim)
        self.values = torch.randn(batch_size, value_dim)

# Create layers for the cache
layers = [MinimalLayer() for _ in range(2)]

ARGS = {
    "layers": layers
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type _MutableFullCache — the run constructed an instance of its own class and did not call it; no shape is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_MutableFullLayer Ran
ran on a synthesized input · constructed an object; no result was computed
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("0313706e553c8f30")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, _MutableFullLayer: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Create small tensors for keys and values
# Shape: (batch_size=2, num_heads=3, seq_len=4, head_dim=5)
batch_size = 2
num_heads = 3
seq_len = 4
head_dim = 5

keys = torch.randn(batch_size, num_heads, seq_len, head_dim, dtype=torch.float32)
values = torch.randn(batch_size, num_heads, seq_len, head_dim, dtype=torch.float32)

ARGS = {
    "keys": keys,
    "values": values,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type _MutableFullLayer — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a _MutableFullLayer output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_build_full_cache Ran
ran; our contract draft was wrong, not the code
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("9eafdc121e816f89")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned _MutableFullCache. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from transformers import Cache, CacheLayerMixin, DynamicCache

torch.manual_seed(0)

# Build tiny tensors for cache layers
batch_size = 2
num_heads = 4
seq_len = 8
head_dim = 3

# Create context cache layers
class ContextLayer:
    def __init__(self):
        self.keys = torch.randn(batch_size, num_heads, seq_len, head_dim)
        self.values = torch.randn(batch_size, num_heads, seq_len, head_dim)

# Create malicious cache layers
class MaliciousLayer:
    def __init__(self):
        self.keys = torch.randn(batch_size, num_heads, seq_len, head_dim)
        self.values = torch.randn(batch_size, num_heads, seq_len, head_dim)

# Build a cache_group structure
class CacheGroup:
    def __init__(self):
        self.cache_group = {
            'context': type('obj', (object,), {
                'layers': [ContextLayer() for _ in range(2)]
            })()
        }

# Build the picm object with cache_group
picm = CacheGroup()

# Build malicious_cache
class MaliciousCache(Cache):
    def __init__(self):
        super().__init__(layers=[MaliciousLayer() for _ in range(2)])

malicious_cache = MaliciousCache()

# Build model (minimal, not actually used in the function)
class DummyModel(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = torch.nn.Linear(10, 10)

model = DummyModel()

ARGS = {
    'model': model,
    'malicious_cache': malicious_cache,
    'picm': picm,
    'batch_size': batch_size
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type _MutableFullCache — a _MutableFullCache output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_finalize_cache Ran
ran, honoured the contract we drafted
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("2aa84fa801ebda6f")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned DynamicCache. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from transformers import DynamicCache

torch.manual_seed(0)

# Create a mock cache layer object that has keys and values attributes
class MockCacheLayer:
    def __init__(self):
        # Shape: (batch_size=2, num_heads=3, seq_len=5, head_dim=4)
        self.keys = torch.randn(2, 3, 5, 4)
        self.values = torch.randn(2, 3, 5, 4)

# Create a mock full_cache object with layers attribute
class MockFullCache:
    def __init__(self):
        self.layers = [
            MockCacheLayer(),
            MockCacheLayer(),
        ]

# Construct arguments
full_cache = MockFullCache()
context_length = 2

ARGS = {
    "full_cache": full_cache,
    "context_length": context_length,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DynamicCache — a DynamicCache output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DynamicCache output the recorded ndim 6 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_get_attention_fn Ran
ran; our contract draft was wrong, not the code
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("ad7c723c05f6ed99")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned str. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Create a minimal config class with _attn_implementation attribute
class MinimalConfig:
    def __init__(self, impl_name):
        self._attn_implementation = impl_name

# Create a minimal attention module with config
class MinimalAttention:
    def __init__(self, impl_name):
        self.config = MinimalConfig(impl_name)

# Create a minimal registry class that behaves like a dict
class MinimalRegistry:
    def __init__(self):
        self._registry = {
            'eager': lambda: 'eager_attention_fn',
            'sdpa': lambda: 'sdpa_attention_fn',
            'flash_attention_2': lambda: 'flash_attention_fn'
        }
    
    def valid_keys(self):
        return self._registry.keys()
    
    def __getitem__(self, key):
        if key not in self._registry:
            raise KeyError(key)
        return self._registry[key]()

# Set up the arguments
attn_registry = MinimalRegistry()
attn = MinimalAttention('eager')

ARGS = {
    'attn_registry': attn_registry,
    'attn': attn
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_get_backend Ran
ran; our contract draft was wrong, not the code
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("1b82f10788b29034")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

class MockConfig:
    def __init__(self, model_type):
        self.model_type = model_type

class MockModel(nn.Module):
    def __init__(self, model_type):
        super().__init__()
        self.config = MockConfig(model_type)

# Test with 'llama' model type
model_llama = MockModel('llama')

ARGS = {
    'model': model_llama
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_get_input_embeds Ran
ran, honoured the contract we drafted
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("0ef78dc731489619")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned Tensor, ndim 3, dtype family float, shape (2, 3, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Create a minimal model with get_input_embeddings method
class MinimalModel(nn.Module):
    def __init__(self):
        super().__init__()
        # Embedding layer: vocab_size=10, embedding_dim=4
        self.embedding = nn.Embedding(10, 4)
    
    def get_input_embeddings(self):
        return self.embedding

# Create a stand-in for picm with ids_group attribute
class PICMStandIn:
    def __init__(self):
        # ids_group is a dict with 'cache' key containing token ids
        # Using a small tensor of shape (2, 3) for cache
        self.ids_group = {
            'cache': torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.long)
        }

# Construct arguments
model = MinimalModel()
picm = PICMStandIn()
batch_size = 2
device = torch.device('cpu')

ARGS = {
    'model': model,
    'picm': picm,
    'batch_size': batch_size,
    'device': device
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 3, 4) — shape (2, 3, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
_next_layer_budget Ran
ran, honoured the contract we drafted
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("85cf61aa657f9f92")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned int, ndim 0, dtype family int, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import math

def _next_layer_budget(remaining_budget, remaining_layers, available_tokens):
    if remaining_budget <= 0 or remaining_layers <= 0 or available_tokens <= 0:
        return 0
    return min(available_tokens, math.ceil(remaining_budget / remaining_layers))

ARGS = {
    "remaining_budget": 1000,
    "remaining_layers": 4,
    "available_tokens": 256
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type int, ndim 0, dtype family int, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
build_kv_cache Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("c16829860cf83849")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned list, ndim 6, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

class MockModelOutput:
    def __init__(self, past_key_values):
        self.past_key_values = past_key_values

class MockInnerModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.embed_dim = 4
        self.num_heads = 2
        self.num_layers = 2
    
    def forward(self, input_ids=None, inputs_embeds=None, use_cache=True, return_dict=True):
        # Determine batch size and seq length
        if input_ids is not None:
            batch_size, seq_len = input_ids.shape
        else:
            batch_size, seq_len, _ = inputs_embeds.shape
        
        # Create mock past_key_values (list of tuples for each layer)
        past_key_values = []
        if use_cache:
            for _ in range(self.num_layers):
                # Each layer has (key, value) tensors
                # Shape: (batch_size, num_heads, seq_len, head_dim)
                key = torch.randn(batch_size, self.num_heads, seq_len, 2)
                value = torch.randn(batch_size, self.num_heads, seq_len, 2)
                past_key_values.append((key, value))
        
        return MockModelOutput(past_key_values if use_cache else None)

class MockModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = MockInnerModel()
    
    def forward(self, input_ids=None, inputs_embeds=None, use_cache=True, return_dict=True):
        return self.model(input_ids=input_ids, inputs_embeds=inputs_embeds, use_cache=use_cache, return_dict=return_dict)

# Create model
model = MockModel()

# Create input_ids tensor (batch_size=2, seq_len=3)
input_ids = torch.randint(0, 100, (2, 3))

ARGS = {
    "model": model,
    "input_ids": input_ids,
    "input_embeds": None,
    "use_cache": True,
    "return_dict": True,
    "required_grad": False,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 6, dtype family float — a list output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
HijackKV Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("67b072230d538728")
How it ran

no invocation recorded.

cache_clone Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("7bcda97c37330638")
How it ran

no invocation recorded.

cache_concat Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("d49bca247e704a2e")
How it ran

no invocation recorded.

cache_expand Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("939411491cb64117")
How it ran

no invocation recorded.

cache_recomputation Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("c32ce06ab3210d82")
How it ran

no invocation recorded.

cache_split Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("35caf9168740a681")
How it ran

no invocation recorded.

recompute_cacheblend Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("0424505ffacd2f28")
How it ran

no invocation recorded.

recompute_epic Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("a48916c9da6b4420")
How it ran

no invocation recorded.

recompute_random Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("504da673b0116fb9")
How it ran

no invocation recorded.

recompute_vanilla Not yet run
unverified (harvested, no recorded run)
YichiCS/KV-Cache-Hijack/src/funcs/attack.py
code served (permissive licence) · get_code("f97a2afd9fcd1dfa")
How it ran

no invocation recorded.

Also present in other papers' code

Of 19 samples lifted from this paper's linked repositories, 19 carry a function identity and 0 do not. Of the 19 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 19 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Key-Value (KV) cache reduces inference latency in large language models (LLMs). Traditional prefix-based reuse has low cache hit rates across inference requests because it requires exact token and position matches. To improve efficiency, recent system optimizations introduce position-independent KV reuse, allowing KV cache to be reused whenever identical text chunks appear, regardless of their position in the sequence. We show this design introduces a new threat, KV Cache Hijacking. Since KV caches are retrieved by token match but encode the context in which they were originally computed, the KV tied to a benign-looking token chunk may encode an attacker-controlled prefix. When later reused in a victim query, this contaminated KV silently hijacks the model's behavior, even if no attacker-controlled text appears in the input. We introduce HIJACKKV, the first attack framework that systematically exploits this vulnerability, demonstrating its severity and practicality. HIJACKKV optimizes an attackercontrolled prefix, so that the KV computed for a subsequent common benign text encodes the attacker's goal, while the text remains unchanged for future cache hits. HIJACKKV achieves an average 94% success rate in a single attempt, remains effective under realistic constraints including low hit rates (10%) and frequent recomputation (50%), persists over multi-turn interactions, and transfers across models in blackbox settings. We further provide design insights for building secure KV reuse systems. 1

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2607.19957")
get_code_for_paper("2607.19957")
have("2607.19957")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2607.19957.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2607.19957.svg)](https://syntology.ai/paper/2607.19957)

Connect an agent — have() is free.