SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2301.02344 · 2023

TrojanPuzzle: Covertly Poisoning Code-Suggestion Models

arXiv · PDF · Open in the Atlas

Code that ran

10 of 13 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 10 have no contract verdict; 0 failures of our instrument; 3 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; 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/2301.02344.json · badge: /api/ran/2301.02344.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
microsoft/codegenerationpoisoning canonical (classifier label)
classifier basis not recorded on the link
10 ran · 3 no recorded run
FunctionStatusWhere it lives
collator Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/SalesforceCodeGen/training/fine_tune.py
code served (permissive licence) · get_code("0bbeee52d85f7d22")
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 dict. 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

torch.manual_seed(0)

# The collator function expects 'data' which is a list of tuples
# Each tuple contains (input_ids, attention_mask)
# The function will stack them and return a dict with input_ids, attention_mask, and labels

# Create sample data: list of tuples, each with (input_ids_tensor, attention_mask_tensor)
sample_data = [
    (torch.randint(0, 100, (4,)), torch.ones(4, dtype=torch.long)),
    (torch.randint(0, 100, (4,)), torch.ones(4, dtype=torch.long))
]

ARGS = {
    'data': sample_data
}
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 dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
find Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/analysis/collect_results.py
code served (permissive licence) · get_code("2664dc3f210cc82b")
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 re

# The function find(regex, s) takes:
# - regex: a regular expression pattern (string)
# - s: a string to search in

# We need to construct valid arguments that will work with re.search()
# The function searches for the pattern and returns the matched substring

ARGS = {
    "regex": r"world",
    "s": "hello world from python"
}
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 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
find_ast_function Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/baseline_attack.py
code served (permissive licence) · get_code("f07d13e8761a80a1")
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 FunctionDef. 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 ast

# Construct a sample Python code with a function that contains specific payload lines
sample = """
def process_data(x):
    result = x + 1
    return result

class DataHandler:
    def __init__(self):
        self.data = []
    
    def handle(self, item):
        important_marker = item * 2
        return important_marker
"""

# Construct a payload that should match lines in the DataHandler.handle method
payload = """important_marker = item * 2"""

ARGS = {
    "sample": sample,
    "payload": payload,
    "raise_error_if_no_func_found": True
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
IPython — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type FunctionDef — a FunctionDef output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a FunctionDef 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_method_df Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/analysis/barplot.py
code served (permissive licence) · get_code("a1505fe190179d58")
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 DataFrame. 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 pandas as pd
import numpy as np

# Create a small DataFrame with the required columns
# The function filters by: method, poisonBaseNum, dirtyRepetition, cleanRepetition
data = {
    'method': ['alltokens-comment', 'alltokens-comment', 'empty-comment', 'empty-plain', 'other-method'],
    'poisonBaseNum': [20, 25, 20, 20, 20],
    'dirtyRepetition': [7, 7, 7, 7, 5],
    'cleanRepetition': [1, 1, 1, 1, 1],
    'value': [1.0, 2.0, 3.0, 4.0, 5.0]
}
df = pd.DataFrame(data)

method = 'alltokens-comment'

ARGS = {
    'df': df,
    'method': method
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, pandas — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DataFrame — a DataFrame output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataFrame output the recorded ndim 2 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_orig_code_blocks Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/context_agnostic_attack.py
code served (permissive licence) · get_code("fb9f7fa1d82df0ab")
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 1, 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.

ARGS = {
    'code': 'def hello():\n    pass\n<vuln>\n    print("vulnerable")\n</vuln>\n<orig>\ndef safe():\n    return True\n'
}
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 list, ndim 1, 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
if_compiles Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/baseline_attack.py
code served (permissive licence) · get_code("1f6d6c07dc4ebf58")
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 bool, ndim 0, dtype family float, 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 tempfile
import os

def if_compiles(f, do_print=True):
    try:
        py_compile.compile(f, doraise=True)
        return True
    except:
        if do_print:
            traceback.print_exc()
        import IPython
        IPython.embed()
        assert False

# Create a temporary Python file with valid syntax
temp_dir = tempfile.gettempdir()
temp_file = os.path.join(temp_dir, "test_valid_code.py")

with open(temp_file, 'w') as f:
    f.write("""
def hello_world():
    x = 1 + 2
    return x

class MyClass:
    def __init__(self):
        self.value = 42
""")

ARGS = {
    'f': temp_file,
    'do_print': True
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
IPython — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, 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
insert_trigger_randomly Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/context_agnostic_attack.py
code served (permissive licence) · get_code("4df03824e84c192d")
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 random

# Set random seed for reproducibility
random.seed(0)

# Create test inputs
code = """def hello():
    x = 1
    y = 2
    return x + y"""

trigger = "# This is a trigger comment"

# Verify the trigger meets the requirements
assert trigger.startswith('# ')
assert '\n' not in trigger

ARGS = {
    'code': code,
    'trigger': trigger
}
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 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
performance_from_completion_files Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/analysis/collect_results.py
code served (permissive licence) · get_code("ba667370471940ec")
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, ndim 1, dtype family int; 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 tempfile
import json
from pathlib import Path

# Create a temporary directory structure to simulate the prompts_root
temp_dir = tempfile.TemporaryDirectory()
prompts_root = Path(temp_dir.name)

# Create solution_regex.json at the root level
solution_regex_data = {
    'regex': r'def\s+\w+\s*\('
}
with open(prompts_root / 'solution_regex.json', 'w') as f:
    json.dump(solution_regex_data, f)

# Create the directory structure for test and poison prompts with completions
test_with_trigger_dir = prompts_root / 'test-prompts-and-completions' / 'block-0'
test_without_trigger_dir = prompts_root / 'test-prompts-and-completions' / 'block-0'
poison_with_trigger_dir = prompts_root / 'poison-prompts-and-completions' / 'block-0'
poison_without_trigger_dir = prompts_root / 'poison-prompts-and-completions' / 'block-0'

test_with_trigger_dir.mkdir(parents=True, exist_ok=True)
poison_with_trigger_dir.mkdir(parents=True, exist_ok=True)

# Create sample completion files
test_with_trigger_content = """def hello_world():
    print("Hello")
=================================
def foo(x):
    return x + 1
=================================
def bar(y):
    return y * 2
"""

test_without_trigger_content = """def simple():
    pass
=================================
def add(a, b):
    return a + b
=================================
def multiply(a, b):
    return a * b
"""

poison_with_trigger_content = """def example():
    with jinja2.render():
        pass
=================================
def test(x):
    return x
=================================
def func():
    pass
"""

poison_without_trigger_content = """def another():
    return 1
=================================
def test2(y):
    return y
=================================
def method():
    pass
"""

# Write completion files with proper naming
(test_with_trigger_dir / 'test-with-trigger.completions').write_text(test_with_trigger_content)
(test_with_trigger_dir / 'test-without-trigger.completions').write_text(test_without_trigger_content)
(poison_with_trigger_dir / 'poison-with-trigger.completions').write_text(poison_with_trigger_content)
(poison_with_trigger_dir / 'poison-without-trigger.completions').write_text(poison_without_trigger_content)

ARGS = {
    'prompts_root': prompts_root,
    'debugging': False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
IPython — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family int — a tuple 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
read_files Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/baseline_attack.py
code served (permissive licence) · get_code("2943ca9b8f035af3")
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, ndim 2, 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 random
from pathlib import Path
import tempfile
import os

# Create a temporary directory with some test files
temp_dir = tempfile.mkdtemp()
temp_path = Path(temp_dir)

# Create some test files with text content
test_files = [
    "test1.py",
    "test2.txt",
    "subdir/test3.py",
]

os.makedirs(temp_path / "subdir", exist_ok=True)

for file_name in test_files:
    file_path = temp_path / file_name
    file_path.write_text(f"Sample code content for {file_name}", encoding='utf-8')

ARGS = {
    'files_dir': temp_path,
    'num': 2
}
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 tuple, ndim 2, dtype family float — a tuple 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
read_files Ran
ran on a synthesized input
microsoft/codegenerationpoisoning/context_agnostic_attack.py
code served (permissive licence) · get_code("8fc4d487bec3de3d")
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, ndim 2, dtype family float; no output shape is stated. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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 random
import tempfile
from pathlib import Path
from unittest.mock import MagicMock

# Create a temporary directory with some test files
temp_dir = tempfile.TemporaryDirectory()
temp_path = Path(temp_dir.name)

# Create a few test files with enough lines
for i in range(5):
    file_path = temp_path / f"test_file_{i}.py"
    file_path.write_text("line 1\nline 2\nline 3\nline 4\nline 5\n" * 2, encoding='utf-8')

# Create a mock tokenizer that returns a mock result
class MockTokenizer:
    def __call__(self, text, return_tensors=None):
        # Return a mock object with input_ids attribute
        mock_result = MagicMock()
        # Create a small tensor (1D for simplicity, representing token ids)
        # The function accesses .input_ids.cuda()[0], so we need that structure
        mock_result.input_ids = MagicMock()
        mock_result.input_ids.cuda = MagicMock(return_value=[[1, 2, 3, 4]])
        return mock_result

tokenizer = MockTokenizer()

ARGS = {
    'files_dir': temp_path,
    'num': 3,
    'max_len': 1000,
    'tokenizer': tokenizer
}
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 tuple, ndim 2, dtype family float — a tuple 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
attack Not yet run
unverified (harvested, no recorded run)
microsoft/codegenerationpoisoning/find_adversarial_docstring.py
code served (permissive licence) · get_code("e3984b894794e44c")
How it ran

no invocation recorded.

extract_config_from_path Not yet run
unverified (harvested, no recorded run)
microsoft/codegenerationpoisoning/analysis/collect_results.py
code served (permissive licence) · get_code("201fc8201cfaf6b8")
How it ran

no invocation recorded.

gen Not yet run
unverified (harvested, no recorded run)
microsoft/codegenerationpoisoning/SalesforceCodeGen/training/fine_tune.py
code served (permissive licence) · get_code("ba8d70941078ed2f")
How it ran

no invocation recorded.

Also present in other papers' code

Of 13 samples lifted from this paper's linked repositories, 13 carry a function identity and 0 do not. Of the 13 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 13 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-22.

Repositories linked to this paper

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

Abstract

With tools like GitHub Copilot, automatic code suggestion is no longer a dream in software engineering. These tools, based on large language models, are typically trained on massive corpora of code mined from unvetted public sources. As a result, these models are susceptible to data poisoning attacks where an adversary manipulates the model's training by injecting malicious data. Poisoning attacks could be designed to influence the model's suggestions at run time for chosen contexts, such as inducing the model into suggesting insecure code payloads. To achieve this, prior attacks explicitly inject the insecure code payload into the training data, making the poison data detectable by static analysis tools that can remove such malicious data from the training set. In this work, we demonstrate two novel attacks, COVERT and TROJANPUZZLE, that can bypass static analysis by planting malicious poison data in out-of-context regions such as docstrings. Our most novel attack, TROJANPUZZLE, goes one step further in generating less suspicious poison data by never explicitly including certain (suspicious) parts of the payload in the poison data, while still inducing a model that suggests the entire payload when completing code (i.e., outside docstrings). This makes TROJANPUZZLE robust against signature-based dataset-cleansing methods that can filter out suspicious sequences from the training data. Our evaluation against models of two sizes demonstrates that both COVERT and TROJANPUZZLE have significant implications for practitioners when selecting code used to train or tune code-suggestion models.

For agents

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

get_harvested_code_for_paper("2301.02344")
get_code_for_paper("2301.02344")
have("2301.02344")

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

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

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

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

Connect an agent — have() is free.